我有一个长度为2的字节数组,他们组成一个长度为16位的二进制数,现在如何用Java求出这个16位二进制数的补码?byte []bytes = ...;
byte []finalBytes = fun(bytes); //如何写fun()方法,finalBytes是求补码的函数
byte []finalBytes = fun(bytes); //如何写fun()方法,finalBytes是求补码的函数
解决方案 »
- 为什么vector需要和synchronized同时使用
- 关于web自动测试工具
- 向上转型有什么好处!有什么用!
- EOFException
- 如何監控頁面的狀態
- Java按钮设计
- 各位请帮忙,那里可以下载visibroker for java?
- 请问一下,如果用Jbuilder在application中画图?
- 编译通过运行为什么出错?
- java程序运行时错误Exception in thread "main" java.lang.NoClassDefFoundError: myjava
- 线程同步问题,帮下!
- 用JAVA循环添加大量数据到Sql Server时出现“Error establishing socket”
for(byte a in bytes ){
byte b = ~a;//取反
....//放入B
}
byte c = B.byteValue();
c = c+1
例如,16bit的-1原码表示形式: [1000 0000 0000 0001]
而计算机内部一直都是补码形式: [1111 1111 1111 1111]
* 根据原码获取补码表示, 如-1的16bit原码bytes[]={(byte)0x80,0x01}
* @param orig 数的原码表示形式,orig[0]是最高8bit.
* @return 补码表示形式
*/
public static byte[] fun(byte[] orig) {
int len = orig.length;
if (1 == len || 2==len || 4==len || 8==len) {
if (0x80 == (bytes[0]&0x80)) { //负数的补码才需要变化
byte[] result = new byte[len];
int carry = 1;
for (int i=len-1; i>0; --i) {
result[i] = (byte)~(orig[i]);
if (1==carry ) {
result[i] = (0xFF==result[i])?0:(byte)(result[i]+1);
carry = (0==result[i]) ? 1 : 0;
}
}
result[0] = (byte)((~orig[0] + carry)|0x80);
return result;
} else {
return Arrays.copyOf(bytes, len);
}
} else {
throw new RuntimeException("Unsupported length");
}
}
int len = orig.length;
if (1 == len || 2==len || 4==len || 8==len) {
if (0x80 == (orig[0]&0x80)) {
byte[] result = new byte[len];
int carry = 1;
for (int i=len-1; i>0; --i) {
result[i] = (byte)~(orig[i]);
if (1==carry ) {
result[i] = (0xFF==result[i])?0:(byte)(result[i]+1);
carry = (0==result[i]) ? 1 : 0;
}
}
result[0] = (byte)((~orig[0] + carry)|0x80);
return result;
} else {
return Arrays.copyOf(orig, len);
}
} else {
throw new RuntimeException("Unsupported length");
}
}
你加这句话的意思是什么?result[0] = (byte)((~orig[0] + carry)|0x80);
这个循环过程没有处理result[0],它是数字的最高8bit,含有符号位,不能与其他等同处理(否则将错误改变符号位);为了保证这一点,在取反后(符号位变成0了),设置符号位(|0x80的作用)。carry是进位处理。你可以用一些值单步跟踪下: -1{(byte)0x80,0x01} -256{(byte)0x81,0x00} -32767{(byte)0xFF,(byte)0xFF}