Java中的Byte转为无符号的Integer

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值