Elegantly Handling Endianess in C++
ethernet and ip are actually big endian, i took an exam today and remembering studying that. either way it doesn't matter as long as you are consistent with your implementation because those OSI layers will never really do anything with your data.
I'm confused.... why not just use the standard C-sockets endianness functions? ntohl, htonl, etc.
Quote:
Original post by Hexxagonal
ethernet and ip are actually big endian, i took an exam today and remembering studying that. either way it doesn't matter as long as you are consistent with your implementation because those OSI layers will never really do anything with your data.
As I mentioned, the standard on the project was to store multibyte data within a packet in little endian. Since I was then directly casting the data to types - the endianess was reversed.
Quote:
Original post by SneftelI'm confused.... why not just use the standard C-sockets endianness functions? ntohl, htonl, etc.
I had not run into endianess issues before and was honestly just not aware of them. As well, not all data is integral. In any case I 'finally' ended up writing similiar functions on my own, since the compiler I am using did not support #pragma packing, so it was impossible to directly cast from a memory dump to the struct.
You can swap a float using htonl(), using casting. The actual integer value doesn't matter.
Doubles is harder, though; gotta treat that as an array.
Why the char*, you may ask? Well, C/C++ aliasing rules allow compilers to re-order code as long as it uses different pointer types, with the exception of char*, which serializes memory access.
*(long*)&myFloat = htonl( *(long*)(char*)&myFloat );
Doubles is harder, though; gotta treat that as an array.
Why the char*, you may ask? Well, C/C++ aliasing rules allow compilers to re-order code as long as it uses different pointer types, with the exception of char*, which serializes memory access.
enum Bool { True, False, FileNotFound };
The following code segment is used to detect the endian of system, so that you don't need to modify you compiler setting from different system.
union EndianTest{ EndianTest(unsigned short x) { m_ShortValue = x; } unsigned short m_ShortValue; unsigned char m_CharValue[2];};EndianTest endian(1);if( endian.m_CharValue[0] == 1 ){ _isBigEndian = false;}else{ _isBigEndian = true;}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement