Converting a multiple 8-bit value to an unsigned char*

I am trying to write code for WASAPI that writes audio data to a buffer.

Here is the buffer to be written to.
 
  unsigned char* pData


I know that the data to be written is a multiple of 8 bits. I need to know how to generate the values so they can be written to pData.

My first goal is to write random noise to the buffer with something similar to the following class, where T is the type that is a multiple of 8 bits.
1
2
3
4
5
6
7
8
9
class Random {
public:
	Random(T low, T high) :function(std::bind(std::uniform_real_distribution<>(low, high), std::default_random_engine())) {}

	double operator()() { return function(); }

private:
	std::function<T()> function;
};


I have a Noise_Gen class with a void pointer to the Random.

 
void* rd;



My question is if I have rd return an unsigned long, how do I feed it into pData?
Last edited on
well, the snarky answer is: don't have random generate unsigned longs, have it generate unsigned chars.

The other answer is to just cast it.
unsigned char * cp;
uint64_t big = 12345689101112ull;
cp = (unsigned char*) &big;
//you can address cp[0] ... cp[7] as 64 bit int has 8 bytes, 0-7 are now accessible here, eg
cout << cp[5];

its more efficient, though, to copy integers into integers.
...

unsigned long * ul = (unsigned long*) &pData;
for(int i = 0; i < something; i++)
{
ul[i] = randomval;
}

basically, you can cast ANY type of pointer to any other pointer type. It is mostly useful in casting anything to bytes (for file writes or networking etc) and back again, but you can slice it however. So your options are to work with it byte wise (slower) and copy each block of bytes from random into the data one by one, or to copy them in blocks one int at a time (sizeof type times faster!). The 8 bytes at a time copy is a big speedup for large byte buffers, if you get into images or other such things that are huge and need to be copied quickly.
Last edited on
Does this work even though big isn't a pointer?

 
cp = (unsigned char*) big;
no, i screwed up and fixed it, I left the & off :)
Shouldn't this unsigned long * ul = (unsigned long*) &pData; be this unsigned long * ul = (unsigned long*) pData;?
yes, I was typing too fast across the board I suppose.
Topic archived. No new replies allowed.