Java的Byte都是有符号的(singed),而Byte又是8位的,如何转为无符号( unsigned)的呢?
素材:
byte a=11010110 (singed : -42 、 unsigned :214)
尝试:
方法一:直接转-- (int)a (失败)
转换前 11010110
(转换,牵涉到符号位的扩展。因为扩展前符号位是1,所以扩展后,高位都是1)
转换后 11111111 11111111 11111111 11010110 ( - 42 )
原码--- 补码 转换
各位取反,在加1,转换成 原码
11111111 11111111 11111111 11010110
(符号) 负
(取反) 00000000 00000000 00000000 00101001
(加1 ) 00000000 00000000 00000000 00101010
方法二:通过IO流 (成功)
我常用IO流来进行一些 进制的转换 。
O(∩_∩)O~
import java.io.ByteArrayInputStream;
public class Test{
public static void main(String[] args) {
byte[] bytes = new byte[]{(byte)-42};
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
int result = in.read();
System.out.println("无符号数: \t"+result);
System.out.println("2进制bit位: \t"+Integer.toBinaryString(result));
}
}
输出
无符号数: 214
2进制bit位: 11010110
方法三:当然是看看 ByteArrayInputStream 的源码了。
ByteArrayInputStream的read源码:
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}
原来是 & 运算呀!!!
修改IO的方式的写法:
public class Test{
public static void main(String[] args) {
byte bytes = -42;
int result = bytes&0xff;
System.out.println("无符号数: \t"+result);
System.out.println("2进制bit位: \t"+Integer.toBinaryString(result));
}
}
稍微解释一下:
(byte) -42
& 0xff
STEP01:(byte)-42
进行扩展:
11111111 11111111 11111111 11010110
STEP02:与运算:
00000000 00000000 00000000 11111111 ( 0xff 也是 0x000000ff)
&
11111111 11111111 11111111 11010110
结果:
00000000 00000000
00000000 11010110 (即是整数214)
之所以会弄这个古怪的的问题,是因为我想得到中文字符串的byte流的二进制形式。想窥探一下不同的编码集的异同。
记录一下:
常
读JDK源码,很有收获!!
4
顶
0
踩
分享到:
2010-04-20 19:42
浏览 34673
评论
qipei 写道
用的着这么麻烦么?
举个例子:
240 肯定超过java里 byte的范围了吧?
先把240转成16进制 然后付给byte就行了么
240的16进制是F0;
byte a = (byte)0xF0;
这样的结果是 -16 。
我的意思将 byte形的 -16 转成 无符号的 240.
PS: 我是经过推理验证,最后找的这个方法;
int a = -16 &0xff;
1 楼
qipei
2010-05-26
用的着这么麻烦么?
举个例子:
240 肯定超过java里 byte的范围了吧?
先把240转成16进制 然后付给byte就行了么
240的16进制是F0;
byte a = (byte)0xF0;