Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert big endian to little endian in C [without using provided func] [closed]

Tags:

c

swap

endianness

I need to write a function to convert big endian to little endian in C. I can not use any library function.

like image 281
Alex Xander Avatar asked Feb 02 '10 05:02

Alex Xander


People also ask

How do you convert big endian to little endian binary?

x = htole32(x); will convert from the host encoding to 32-bit little-endian. This is useful for writing little-endian data.

How do you convert to little endian?

Quickly converting to little-endian. If I want to quickly convert a string of data in to little-endian, I just swap each pair of characters (working from right-to-left), then reverse the string.

What is Byteswap?

As mentioned in the comments, byteswapping is the process of changing a values endianess from one to another. Lets say you have a value in your memory (left address is lowest): DE AD BE EF <- big endian. This valu econsists of 4 bytes - in hexadecimal representation two digits are one byte.

Does x86 64 use little endian?

The x86 processors use little-endian byte ordering. The least significant byte (LSB) of an integer is stored at the lowest address of the integer. The most significant byte is stored at the highest address for data items in this processor. For example, byte 7 is the most significant byte for 64-bit processors.


2 Answers

Assuming what you need is a simple byte swap, try something like

Unsigned 16 bit conversion:

swapped = (num>>8) | (num<<8);

Unsigned 32-bit conversion:

swapped = ((num>>24)&0xff) | // move byte 3 to byte 0                     ((num<<8)&0xff0000) | // move byte 1 to byte 2                     ((num>>8)&0xff00) | // move byte 2 to byte 1                     ((num<<24)&0xff000000); // byte 0 to byte 3

This swaps the byte orders from positions 1234 to 4321. If your input was 0xdeadbeef, a 32-bit endian swap might have output of 0xefbeadde.

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

like image 198
Sam Post Avatar answered Oct 14 '22 14:10

Sam Post


By including:

#include <byteswap.h> 

you can get an optimized version of machine-dependent byte-swapping functions. Then, you can easily use the following functions:

__bswap_32 (uint32_t input) 

or

__bswap_16 (uint16_t input) 
like image 45
Amir Mgh Avatar answered Oct 14 '22 15:10

Amir Mgh