Home > other >  How to convert one byte and 4 bits from another byte to a short using bitwise?
How to convert one byte and 4 bits from another byte to a short using bitwise?

Time:05-04

Using bitwise, how could we convert these 3 bytes to two shorts in this pattern in the most performant way?:
(11111111)(01111110)(10000001) 3 bytes
(111111110111)(111010000001) 2 shorts
Found a way to combine two bytes into a short, but for a combination of 1 byte and 4 bits tried a variety of ways for hours with no success. Thanks for your help.

byte byt1 = -1; // 11111111
byte byt2 = 126;// 01111110
byte byt3 = 129;// 10000001
short s_1_2 = (short) ((byt1 << 8) | (byt2 & 0xFF));
// value is 1111111101111110
short s1 = // want to be 111111110111
short s2 = // want to be 111010000001

CodePudding user response:

One of the possibilities is the following:

short s1 = (short) (((byt1 & 0xff) << 4) | ((byt2 & 0xf0) >> 4));
short s2 = (short) (((byt2 & 0x0f) << 8) | (byt3 & 0xff));
  • Related