Since endianness is implementation defined, it is safe to assume that you are talking about an implementation and not C standard. Looking at the links you have sent, I think you refer to Linux and GNU C compiler.
Then under this implementation it is safe to first type pun the signed int
to unsigned int
, change the endianness and type pun it back.
Following is one way of doing it
union signed_unsigned {
signed long a;
unsinged long b;
} converter;
signed long to_convert = .... //whatever value
converter.a = to_convert;
converter.b = htonl(converted.b);
to_convert = converter.a;
You can make this into a macro or a function as you see fit.
As suggested by @underscore_d, the other way to type pun a signed long
to unsigned long
(and back) is using pointer cast. That is valid in both C and C++ (although in C++ you should use reinterpret_cast
rather than C style pointer casts).
You can use the following way to achieve the same.
signed long to_convert = .... //whatever value
unsigned long temp = *(unsinged long*)&to_convert;
temp = htonl(temp);
to_convert = *(signed long*)&temp;