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

用Java将字节转换为二进制

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

用Java将字节转换为二进制

String toBinary( byte[] bytes ){    StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);    for( int i = 0; i < Byte.SIZE * bytes.length; i++ )        sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');    return sb.toString();}byte[] fromBinary( String s ){    int sLen = s.length();    byte[] toReturn = new byte[(sLen + Byte.SIZE - 1) / Byte.SIZE];    char c;    for( int i = 0; i < sLen; i++ )        if( (c = s.charAt(i)) == '1' ) toReturn[i / Byte.SIZE] = (byte) (toReturn[i / Byte.SIZE] | (0x80 >>> (i % Byte.SIZE)));        else if ( c != '0' ) throw new IllegalArgumentException();    return toReturn;}

也有一些更简单的方法来处理此问题(假定为大字节序)。

Integer.parseInt(hex, 16);Integer.parseInt(binary, 2);

Integer.toHexString(byte).subString((Integer.SIZE - Byte.SIZE) / 4);Integer.toBinaryString(byte).substring(Integer.SIZE - Byte.SIZE);


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

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

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