Combining two bytes in Java

旧时模样 提交于 2019-12-10 18:45:08

问题


Having two bytes, how to make a new byte by taking the first 3 bits from the first byte and the last 5 from the second ?

For instance, how would that for 11100000 and 00011111 ==> 11111111 ?

I am using Java.


回答1:


byte b1, b2;

take first 3 bits: b1 & 0xE0

take last 5 bits: b2 & 0x1F

concatenate: b1 | b2




回答2:


You can use the BitSet class. There's an example in here.




回答3:


Using the masks 0xE0 (11100000) and 0x1F (00011111), you can mask out the bits you don't want and bitwise or them together:

byte b1 = 123; // 01111011
byte b2 = 50;  // 00110010

byte b3 = (b1 & 0xE0) | (b2 & 0x1F);  // = 114  01110010



回答4:


(b1 & 0xe0) | (b2 & 0x1f)



来源:https://stackoverflow.com/questions/11947138/combining-two-bytes-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!