views:

67

answers:

3

I want to copy a float buffer into a char (byte) buffer without allocating memory for two separate buffers. In another words I want to use one buffer and copy in place. The Problem is that if I need a float buffer then in order to copy that to a char then I will need a char* pointer; If I were copying from float* to float* it would be easy as I would just pass in the same pointer for the target and the source.

eg.

void CopyInPlace(float* tar, float* src, int len) {
....
}
CopyInPlace(someBuffer, someBuffer, 2048);

void PackFloatToChar(char* tar, float* src, int len) {

}
????????

How would I do this?

Does memcpy copy in place?, if passed in the same pointer?

+1  A: 

Your question seems a bit confused.

Do you want to simply interpret an array of floats as a char array (for something like writing to a file?). If so, simply cast. All pointers in C can be represented by char*'s.

memcpy will copy from one memory location to another. But keep careful track of whether your "len" parameter is the number of floats or number of bytes. If "len" is the count of floats in the array, multiply it by sizeof(float) in the memcpy call.

jkerian
ah ok memcpy works. However, what is the algorithm for unpacking the bytes to floats? I will post this as my next question. Thanks!
juxstapose
@juxstapose You cannot use memcpy to copy to the same buffer. You need memmove of the source/destination overlap.
nos
+3  A: 

If you want to convert a float pointer to a char pointer, a cast is sufficient.

float* someBuffer;
...
char* someBuffer2 = (char*)someBuffer;
KennyTM
+1  A: 

As an alternative to the casting that's already been recommended, you might want to consider using a union, something like:

union x { 
    float float_val;
    char bytes[sizeof(float)];
};

There isn't likely to be a huge difference either way, but you may find one more convenient or readable than the other.

Jerry Coffin
The big difference with gcc is that this solution circumvents the strict aliasing rule. With another compiler it is not guaranteed, because accessing an union through another field than it was last written to is just as undefined as casting pointers and then accessing them in the standard.
Pascal Cuoq