栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Java中将字节数组转换为整数,反之亦然

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Java中将字节数组转换为整数,反之亦然

byte[] toByteArray(int value) {     return  ByteBuffer.allocate(4).putInt(value).array();}byte[] toByteArray(int value) {    return new byte[] {         (byte)(value >> 24),        (byte)(value >> 16),        (byte)(value >> 8),        (byte)value };}int fromByteArray(byte[] bytes) {     return ByteBuffer.wrap(bytes).getInt();}// packing an array of 4 bytes to an int, big endian, minimal parentheses// operator precedence: <<, &, | // when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to rightint fromByteArray(byte[] bytes) {     return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);}// packing an array of 4 bytes to an int, big endian, clean preint fromByteArray(byte[] bytes) {     return ((bytes[0] & 0xFF) << 24) |  ((bytes[1] & 0xFF) << 16) |  ((bytes[2] & 0xFF) << 8 ) |  ((bytes[3] & 0xFF) << 0 );}

将带符号的字节打包为一个int时,每个字节都需要屏蔽掉,因为由于算术提升规则(在JLS,转换和提升中所述),它被符号扩展为32位(而不是零扩展)。

Joshua Bloch和Neal Gafter在Java Puzzlers
(“每个字节都有很大的乐趣”)中描述了一个与此有关的有趣难题。在将字节值与int值进行比较时,将字节符号扩展为int,然后将该值与另一个int进行比较

byte[] bytes = (…)if (bytes[0] == 0xFF) {   // dead pre, bytes[0] is in the range [-128,127] and thus never equal to 255}

请注意,所有数字类型都用Java签名,但char是16位无符号整数类型。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/414908.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号