Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Little and Big Endian in Java (android)

I'm building an app using Android Studio and in my project, I need to do a lot of conversions like short/int to byte arrays. I also want my app to receive data from a robot which is coded in C, and the robot sends a structure which has a lot of uint16-32, int16-32.... I found a lot of posts and codes that helped me convert my attributes in bytearray but I always see people talking about Little and Big Endian and i can't grasp the difference. If someone could explain it to me .... NB :the robot sends data through a Wifi socket with TCP protocol

like image 445
Sech Avatar asked Oct 28 '25 02:10

Sech


2 Answers

Little Endian and Big Endian simply refer to the order in which the bytes of a data structure are presented.

Imagine for a moment that you have a 16-bit integer that is represented by the hexidecimal value 0xabcd. Because 8 bits = 1 byte, we have our integer is composed of two bytes, ab and cd. In a Big Endian system, the most significant bytes are placed in the lower memory address, while in Little Endian systems, we put them in the higher one.

To show this visually, assume we've put our integer at the memory address 0.

In a Big Endian system, our memory would look like this:

Memory address  -> |  0 |  1 |
Value           -> | ab | cd |

In a Little Endian system, it would look like this:

Memory address  -> |  0 |  1 |
Value           -> | cd | ab |

Traditionally, network byte order is Big Endian.

like image 81
Josh Hebert Avatar answered Oct 30 '25 17:10

Josh Hebert


When converting an integer to a byte stream, the integer is usually divided into bytes and the bytes are sent one by one. If the first byte sent contains the least significant bits, it is little endian. If the first byte sent contains the most significant bits, it is big endian. In little endian, 1 would be represented by the bytes 1 followed by a byte containing 0. (Since bytes can be represented by two hexadecimal digits, they are often represented this way.) So the short integer 1 is converted into the bytes 01 00 and the short integer 256 becomes the bytes 00 01 in little endian. In big endian, the byte stream for 1 is 00 01 and 256 becomes 01 00.

See https://en.wikipedia.org/wiki/Endianness

like image 31
Bradley Ross Avatar answered Oct 30 '25 17:10

Bradley Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!