简体   繁体   中英

C Language - [copy in place] float* to char* and the reverse

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?

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

float* someBuffer;
...
char* someBuffer2 = (char*)someBuffer;

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM