Java中的Byte转为无符号的Integer

来源:互联网 发布:南方全站仪数据采集 编辑:程序博客网 时间:2024/06/13 20:06
 

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源码,很有收获!!

原创粉丝点击