gtdevel
gtdevel

Reputation: 1513

Converting sections of byte arrays to integer values

I am currently making an android application which accepts bluetooth measurement from a device. The way the data is packaged is in 4 bytes. I need to get two values out of these bytes.

First value is made up of: 6bit and 7bit of first byte and bit 0 to bit 6 of byte 2

Second values is simpler and consists of the full 3rd byte.

What is a good way to access these bit values, combine them and convert them to integer values? Right now i'm trying to convert from byte array to bitset, and then access individual bits to create new bytes that would then be converted to a integer.

Thanks, and please ask if I am not being clear enough.

Upvotes: 0

Views: 3016

Answers (2)

gtdevel
gtdevel

Reputation: 1513

I figured it out: I converted the byte array to int using this method

public static int byteArrayToInt(byte[] b, int offset) { 
   int value = 0; 
   for (int i = 0; i < 4; i++) { 
      int shift = (4 - 1 - i) * 8; 
      value += (b[i + offset] & 0x000000FF) << shift; 
   } 
   return value; 
} 

Then I used the method pokey described. Thanks for your help!

Upvotes: 2

pokey909
pokey909

Reputation: 1837

im not sure if i understood your format correctly. Does this bitmask correspond to your first value?

0xC07F0000

That is bits 16-22,30,31 (zero based indexing used here, i.e. bit 31 is last bit).

Another thing, is your value expected to be signed or unsigned?

Anyway, if it is the way i assume then you can convert it like this with some bitmasks:

unsigned int val = 0xdeadbeef;

unsigned int mask1 = 0xC0000000;
unsigned int mask2 = 0x007F0000;

unsigned int YourValue = (val&mask1)>>23 | (val&mask2)>>16;

Do that in the same way with your other values. Define a bitmask and shift it to the right. Done.

Cheers

Upvotes: 1

Related Questions