I’ve recently been assigned to a C++ project involving information being sent between computers via UDP. When a packet arrives, I have a program which accepts the data and can display it as a raw hexadecimal string. However, I’m struggling to grasp exactly how this whole process is supposed to work. The hex string supposedly contains several fields (e.g. a 4-char array, some float_32s, and some uint_32s).
How do I translate the sections of this string into the correct variable types? The first value, an ASCII title, was simple enough; the first eight chars in the hex string are a hexadecimal representation of an ASCII word (0x45 hex can be translated directly to the capital letter E). But the next value, a 32-bit float, doesn’t really make sense to me. What is the relation between the hex value “42 01 33 33” and the float value “32.3” (a given example)?
I’m a bit in over my head here, I feel I’m missing some essential information regarding the way number systems work.
All types in C have a representation (which for most types is defined by a particular implementation). Most C implementations use IEEE 754 for representing the floating types (this may actually be a requirement for C and C++, but from memory it is not). The Wikipedia article explains how the floating types are represented in memory. In most C and C++ implementations,
floatis a 32-bit type anddoubleis a 64-bit type. Therefore, in these implementationsfloatis 4 bytes wide anddoubleis 8 bytes wide.Be careful, because the byte order can be different. Some architectures store the floating type in little endian, some in big endian. There is also a Wikipedia article on endianness too.
To copy the bytes to the floating type, you have to make sure that the floating type is the same size as the number of bytes you have, and then you can copy the bytes one-by-one ‘into’ the floating type. Something like this will give you the gist of it:
There are other ways of copying the bytes to the floating type, but be careful about ‘breaking the rules’ (type-punning etc.). Also, if the resulting value is incorrect, it may be because the byte order is wrong, and therefore you need to copy the bytes in reverse, so that the 4th byte in the representation is the 1st byte of the float.