C Function to Convert float to byte array

后端 未结 6 898
天命终不由人
天命终不由人 2020-12-04 22:42

I\'m trying to make a function that will accept a float variable and convert it into a byte array. I found a snippet of code that works, but would like to reuse it in a func

6条回答
  •  春和景丽
    2020-12-04 23:16

    Here's a way to do what you want that won't break if you're on a system with a different endianness from the one you're on now:

    byte* floatToByteArray(float f) {
        byte* ret = malloc(4 * sizeof(byte));
        unsigned int asInt = *((int*)&f);
    
        int i;
        for (i = 0; i < 4; i++) {
            ret[i] = (asInt >> 8 * i) & 0xFF;
        }
    
        return ret;
    }
    

    You can see it in action here: http://ideone.com/umY1bB

    The issue with the above answers is that they rely on the underlying representation of floats: C makes no guarantee that the most significant byte will be "first" in memory. The standard allows the underlying system to implement floats however it feels like -- so if you test your code on a system with a particular kind of endianness (byte order for numeric types in memory), it will stop working depending on the kind of processor you're running it on.

    That's a really nasty, hard-to-fix bug and you should avoid it if at all possible.

提交回复
热议问题