I need to write a function to convert big endian to little endian in C. I can not use any library function.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
If you are running on a x86 or x86_64 processor, the big endian is native. so
for 16 bit values
for 32 bit values
This isn't the most efficient solution unless the compiler recognises that this is byte level manipulation and generates byte swapping code. But it doesn't depend on any memory layout tricks and can be turned into a macro pretty easily.
EDIT: This function only swaps the endianness of aligned 16 bit words. A function often necessary for UTF-16/UCS-2 encodings. EDIT END.
If you want to change the endianess of a memory block you can use my blazingly fast approach. Your memory array should have a size that is a multiple of 8.
This kind of function is useful for changing the endianess of Unicode UCS-2/UTF-16 files.
This code snippet can convert 32bit little Endian number to Big Endian number.
If you need macros (e.g. embedded system):
Edit: These are library functions. Following them is the manual way to do it.
I am absolutely stunned by the number of people unaware of __byteswap_ushort, __byteswap_ulong, and __byteswap_uint64. Sure they are Visual C++ specific, but they compile down to some delicious code on x86/IA-64 architectures. :)
Here's an explicit usage of the
bswap
instruction, pulled from this page. Note that the intrinsic form above will always be faster than this, I only added it to give an answer without a library routine.Assuming what you need is a simple byte swap, try something like
Unsigned 16 bit conversion:
Unsigned 32-bit conversion:
This swaps the byte orders from positions 1234 to 4321. If your input was
0xdeadbeef
, a 32-bit endian swap might have output of0xefbeadde
.The code above should be cleaned up with macros or at least constants instead of magic numbers, but hopefully it helps as is
EDIT: as another answer pointed out, there are platform, OS, and instruction set specific alternatives which can be MUCH faster than the above. In the Linux kernel there are macros (cpu_to_be32 for example) which handle endianness pretty nicely. But these alternatives are specific to their environments. In practice endianness is best dealt with using a blend of available approaches