java bitwise是什么_Java – Bitwise操作使我困惑,它有效,但我认为它不应该

我一直在玩按位操作以便紧凑地存储有关对象的信息,我打算做的是有一个short [] [],每个条目存储两条信息,即第一组位(8或者4)包含信息,然后剩余的比特(分别为8或12)存储其余的.

在下面的代码中,我演示了我提到的两个例子,要遵循的问题;

private void test1() {

// This test takes a 16 bit binary number and breaks it into two

// bytes of 8 bits. It then takes the bytes and sticks them back

// together then outputs their decimal value

String st = "0011111100110111";

short s = Short.parseShort(st,2);

byte[] ba = new byte[] {

(byte)(s & 0xFF),

(byte)((s >>> 8) & 0xFF)

};

System.out.println(s);

System.out.println(ba[0]);

System.out.println(ba[1]);

byte b0 = ba[0];

byte b1 = ba[1];

short sh = (short)((b1 << 8) | b0);

System.out.println(sh);

}

private void test2() {

// This test takes two shorts and sticks them together in a

// 4 bit 12 bit configuration within a short, it then breaks

// them apart again to see if it worked!

short s0 = 4095;

short s1 = 15;

short sh = (short)((s1 << 12) | s0);

System.out.println(sh);

short[] sa = new short[] {

(short)(sh & 0xFFF),

(short)((sh >>> 12) & 0xF)

};

System.out.println(sa[0]);

System.out.println(sa[1]);

}

我主要担心的是在test2()中我希望只能使用有符号值,但是我似乎能够使用4095的值为12位,15位为4位(我预期的范围是-2048到2047和-8到7),它是如何运用这些价值观的,我错过了什么?

另外还有一个问题,为什么我不能在test1()中使用1011111100110111?

最后,以这种方式存储信息是一个好主意吗?阵列将是大约500×200或1000x 500之类的东西.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值