java中如何将字节分组,如何在Java中为变量分配2个字节?

在Java中,如果你需要存储两个字节,你可以使用short类型,它占用16位(2个字节)。例如,可以将高位字节通过左移8位然后与低位字节进行按位或操作来组合。对于单独字节的位操作,可以使用右移和按位或来设置特定位。这种技巧常用于位操作和数据打包。
摘要由CSDN通过智能技术生成

How can I assign 2 bytes to a variable in Java? I know I can do this:

byte val = 2; // this is one byte with 0000 0010

But I need to assign 2 bytes to val. How can I do this?

解决方案

As well as using an array of two bytes, you can use a short, which is guaranteed by the Java language spec to be 16 bits wide.

short x = 0x1234s; // assigns 0x34 to the lower byte, 0x12 to the higher byte.

If you have two bytes that you want to combine into a short, you'll need

shift the higher byte by 8 bits and combine them with bitwise or:

byte b1 = 0x12;

byte b2 = 0x34;

short x = ((short)b1 << 8) | b2;

If you want to assign different bits to a single byte variable, then you do that with the right-shift and bitwise or operators as well. Bit n is identified by (1<

byte b = (1<<3)|(1<<2); // b is set to 0000 1100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值