swap - convert big endian to little endian in C [without using provided func] -
I need to directly write a function to convert the big endian into a little endian. I can not use any library function
Assume that you need a simple byte swap,
Unsigned 16 bit conversion:
swap = (num 8) | (Num & lt; & lt; 8);
Unsigned 32-bit conversion:
swap = ((num> gt; 24) & 0xff). // move byte 3 to byte 0 ((num & lt; & lt; 8) & 0xff0000). // move byte 1 to byte 2 (number (gt; & gt; 8) & 0xff00). // step byte 2 to byte 1 ((num & lt; 24) & 0xff000000); // byte 0 to byte 3
This changes the byte order from 1234 to 4321. If your input was 0xdeadbeef
, the 32-bit endangered swap may be 0xefbeadde
output.
The above code should be cleaned with macros or at least constants instead of magic numbers, but hopefully it helps edit
: as In another reply, the platforms, OS, and instructions set specific options that can be much faster than the above. There are macros in the Linux kernel (for example cpu_to_be32) which handle Endianance very well. But these options are specific to their environment. The best method is to use a mixture of methods available in Practical Endurance.
Comments
Post a Comment