0

I am using RakNet for networking and I need to transmit float values. The problem is, that I can only send single bytes. Since float is composed out of 4 bytes, I thought it must be possible, to tear the float down into these four bytes and send them. After that, I want to compose them together again to a float.

How do I do that?

1 Answers1

6
  1. memcpy the original float value to an appropriately sized array of unsigned chars

    float f = ...;
    
    unsigned char c[sizeof f];
    memcpy(c, &f, sizeof f);
    // use `c[i]` to access the bytes
    
  2. Reinterpret the original pointer as an array of unsigned chars using reinterpret_cast

    float f = ...;
    
    unsigned char *c = reinterpret_cast<unsigned char *>(&f);
    // use `c[i]` to access the bytes
    
  3. Use a union to perform the same reinterpretation

    union FC {
      float f;
      unsigned char c[sizeof FC::f];
    };
    
    float f = ...;
    
    FC u = { f };
    // use `u.c[i]` to access the bytes
    

Just keep in mind a few extra details: the last approach (with union) is now legal in C, but is still formally illegal in C++ - you are not allowed to read "inactive" members of unions in C++. Observe the byte ordering on little- vs. big-endian platforms. If you use the second approach, also reinterpret the recipient float as an array of unsigned chars and not the other way around to avoid alignment issues.

AnT
  • 302,239
  • 39
  • 506
  • 752
  • I wouldn't use memcpy function because it is a very risky function from the point of view of security. ;) – NKN Dec 24 '13 at 17:41
  • @NKN: There's nothing risky about it if you know what you are doing. "Risky" functions are the functions that do not offer you any chance to prevent problems (like `gets` or `atoi`, for example). `memcpy` does not belong to that category. – AnT Dec 24 '13 at 17:42
  • Thanks for your answer. The first method sounds like the easiest. But how do you make a float again out of these bytes? –  Dec 24 '13 at 17:45
  • @Liess Jemai: In the first method, you just `memcpy` it back from char array to a `float` object. In the second method... well, you have to be careful: reinterpret the target `float` object as an array of char and write the data there. In the third method, you simply do it backwards: store the bytes into `u.c` and then read `u.f`. – AnT Dec 24 '13 at 22:58
  • 1
    @zhiayang: Reinterpreting char array as a float is not a good idea: it does not guarantee that the alignment requirements are met and it is generally illegal. – AnT Dec 24 '13 at 22:59