Edwin
Edwin

Reputation: 827

Convert 2's complement byte to unsigned positive value in Java

I have an 8 bit byte array in Java. The byte array consists of the high and low bytes of a 16 bit number that it's receiving from an external sensor.

For example, the byte array might be the following:

00 00 00 01 00 02 00 03
0  1  2  3  4  5  6  7

In the byte array above, each even index is a high byte of a 16 bit number and each odd index is the low byte.

The issue I am having is when the number gets larger than 127, causing the 2's complement representation of the number to prevail. What I really wish to do is to keep the POSITIVE unsigned number. Hence I don't care for 2's complement. Here is what I've tried to do without success.

byte[] buffer = new byte[1024]; 

//SOME CODE SNIPPET THAT PUTS NUMBERS B/W 0-500 INTO THE BUFFER RANDOMLY

for(int i = 0; i < 1024; i+=2) {
    int twoByte = 0;
    short high = 0, low = 0;
    high = (short)buffer[i];
    low = (short)buffer[i+1];
    twoByte = ((high << 8) | low);
    System.out.println(twoByte);
}

I have tried to convert to a short to make the 8 bit digit unsigned, but seems java truncates the leading 0's ad treats it as a 8 bit and keeps the negative sign. Does anyone know maybe a better method?

## EDIT: I don't know if it matters, but it might be worth mentioning that this is an application running on Android.##

Cheers,

Upvotes: 2

Views: 4906

Answers (2)

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

Try:

int high = ((int)buffer[i]) & 0xff;
int low = ((int)buffer[i+1]) & 0xff;

int twoBytes = (high << 8) | low;

Sample code:

byte[] buffer = new byte[] { (byte) 0x16, (byte) 0xfa };

int high = ((int)buffer[0]) & 0xff;
int low = ((int)buffer[1]) & 0xff;
int twoBytes = (high << 8) | low;

Values:

buffer   = [ 22, -6 ]
high     = 22
low      = 250
twoBytes = 5882 

5882 is 0x16fa as hexadecimal, it works.

Check that you correctly read the bytes from your sensor.

Upvotes: 5

Austin
Austin

Reputation: 21

To convert a number from two's complement to unsigned:

if(x<0)
{
    x=256+x;
}

Upvotes: 2

Related Questions