Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LSB/MSB handling in Java

If I have to handle values to be stored in bytes like 0x118, how do I split the LSB and MSB?

I was trying the following way... I don't think that it's the right way:

value = 0x118;  

Storing in bytes...

result[5] = (byte) value;  
result[6] = (byte)(value << 8);  
...

What is the correct way?

like image 240
Arun Abraham Avatar asked Mar 02 '11 11:03

Arun Abraham


People also ask

What is MSB and LSB in Java?

LSB - Least Significant Bit, MSB - Most Significant Bit (but Arun wants to split a short into bytes)

What is MSB in Java?

The most significant bit (MSB) is the bit in a multiple-bit binary number with the largest value. This is usually the bit farthest to the left, or the bit transmitted first in a sequence. For example, in the binary number 1000, the MSB is 1, and in the binary number 0111, the MSB is 0.

What is MSB and LSB give example?

Digital data is binary, and like ordinary numerical notation, the left end is the highest digit, while the right end is the lowest digit. For example, 99 in the decimal system is expressed as (MSB)01100011(LSB) in the binary system. In this case, the MSB is 0 and the LSB is 1.

How do you calculate MSB and LSB?

In a binary number, the bit furthest to the left is called the most significant bit (msb) and the bit furthest to the right is called the least significant bit (lsb). The MSB gives the sign of the number (sign bit) , 0 for positive and 1 for negative.


1 Answers

This will do it:

result[5] = (byte) (value & 0xFF);           // Least significant "byte"
result[6] = (byte) ((value & 0xFF00) >> 8);  // Most significant "byte"

I usually use bit masks - maybe they're not needed. The first line selects the lower eight bits, the second line selects the upper eight bits and shifts the bits eight bit positions to the right. This is equal to a division by 28.


This is the "trick" behind:

  (I) LSB

  01010101 10101010        // Input
& 00000000 11111111        // First mask, 0x00FF
  -----------------
  00000000 10101010        // Result - now cast to byte

  (II) MSB

  01010101 10101010        // Input
& 11111111 00000000        // Second mask, 0xFF00
  -----------------
  01010101 00000000        // Result - 
  >>>>>>>>                 // "Shift" operation, eight positions to the right
  -----------------
  00000000 01010101        // Result - now cast to byte

To sum it up, do the following calculation:

 byte msb = result[6];
 byte lsb = result[5];
 int result = (msb << 8) + lsb;    // Shift the MSB bits eight positions to the left.
like image 166
Andreas Dolk Avatar answered Sep 28 '22 09:09

Andreas Dolk