byte 与 int 转换
来源:互联网 发布:cfd流体分析软件 编辑:程序博客网 时间:2024/06/04 18:47
复习过程中,遇到的不太理解的地方
(byte)b & 0xff
byte to int
比较下面两个
public static int byte2Int(byte b){ return (int)b; } public static int byte2Int(byte b){ return (int)(b & 0xff); }
疑问
你肯定在想这个与操作有什么影响吗?
是的,有影响 。以下是我的理解
& 0xff
0xff 的功能其实是补全32位int的byte b = 11111111 ; // 脑袋里想的二进制表示 -1b & 0xff 结果是: 000...000(24个)11111111这样,得到的32位int值是用24个0补全的,所以我们得到的int值为 255
(int) b
没有与操作,我们可以考虑它是如何补全32位int的:若b表示负数,则用1补全位数,111111111...111(32个) 此为补码,补码求原码:符号为1,其余位取反加1.还是 -1
所以,byte转int我们要理解是否考虑符号位。
强制类型转换较常用。
int 转 byte ,只需截取int的低8位即可
可以看到& 0xff 这一操作其实是保持了byte二进制的表示,这一特点我们后面会提到。
byte[] to int
如果说 byte 转 int 要考虑符号位,那么byte数组呢(4个byte转换1个int)
这时,我们要保持二进制的表示,什么意思呢
4个byte: -1 2 3 4-1: 111111112 : 000000103 : 000000114 : 00000100得到的int值为该二进制表示拼接而成(方便理解)11111111 00000010 00000011 00000100值为多少,就要看高位低位了(大端小端)。
从这里可以看出,byte 拼接的过程中可以使用 & 0xff
// byte数组长度为4, bytes[3]为高8位public static int bytes2Int(byte[] bytes){ int value=0; value = ((bytes[3] & 0xff)<<24)| ((bytes[2] & 0xff)<<16)| ((bytes[1] & 0xff)<<8)| (bytes[0] & 0xff); return value;}
int to byte[]
public static byte[] int2Bytes( int value ) { byte[] src = new byte[4]; src[3] = (byte) ((value>>24) & 0xFF); src[2] = (byte) ((value>>16) & 0xFF); src[1] = (byte) ((value>>8) & 0xFF); src[0] = (byte) (value & 0xFF); return src; }
阅读全文
0 0
- byte[]与int转换
- byte 与 int 转换
- java int 与 byte转换
- c# int与byte[]转换
- Int与Byte的转换
- byte与int强制转换
- int 与 byte[] 的相互转换
- int 与 byte[] 的相互转换
- int 与 byte[] 的相互转换
- int、char、double与byte相互转换
- int、char、与byte相互转换
- int、char、double与byte相互转换
- int、char、double与byte相互转换
- c++ int与byte数组进行转换
- int 与 byte[] 的相互转换
- byte与int转换之类的函数
- java byte 与int的互相转换
- int与byte数组相互转换
- python中关于if name == 'main'
- mysql最新配置
- 登录后台逻辑三之session和cookie
- Linux之分段机制和分页机制
- python 验证码
- byte 与 int 转换
- [编程题] 赶去公司
- SWFTOOL安装过程及可能出现的问题
- 输出4+44+444+4444
- C++使用过程中容易忽略的小细节
- 导入jquery在线库和离线库
- USB协议[转]__总结得很好
- 100.64.0.0/10 运营商级NAT(Carrier-grade NAT)共享地址空间
- 写优雅代码之聊一聊抽象类2