0

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.

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank you very much pokey. The only thing is that I receive the results from the bluetooth device as a byte[] array. Can I make that into an integer and then use your process?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.