当前位置: 代码迷 >> J2SE >> byte->Hex,该怎么处理
  详细解决方案

byte->Hex,该怎么处理

热度:291   发布时间:2016-04-24 13:10:35.0
byte-->Hex
RT:byte字节数组怎么转换成16进制!

------解决方案--------------------
Java code
public class Test {    public static void main(String args[]) {                String str = "Hello";        byte[] b = str.getBytes();        System.out.println(byte2HexString(b));    }        public static String byte2HexString(byte[] b) {        char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',                      '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};        char[] newChar = new char[b.length * 2];        for(int i = 0; i < b.length; i++) {            newChar[2 * i] = hex[(b[i] & 0xf0) >> 4];            newChar[2 * i + 1] = hex[b[i] & 0xf];        }        return new String(newChar);    }}
------解决方案--------------------
hello 的 5 个 byte 是:

0x48 0x65 0x6C 0x6C 0x6F

以第一个字节:0x6C 为例:

(b[i] & 0xf0) >> 4
(0x6C & 0xf0) >> 4 可以获得高 4 位,即 0x6

01101100 0x6C
& 11110000 0xF0
------------------
01100000 0x60

再将 01100000 左移 4 位就得到了 0110 即 0x6

hex[0x6] 取数组中的索引为 6 的字符,即“6”

b[i] & 0xf
0x6C & 0xf 可以获得低 4 位,即 0xC
hex[0xC] 取数组中的索引为 12 的字符,即“C”

这样就完成一个字节的转换。
------解决方案--------------------
3 楼的倒数第六行错了:

“再将 01100000 左移 4 位就得到了 0110 即 0x6”应改为:

再将 01100000 右移 4 位就得到了 0110 即 0x6
------解决方案--------------------
Java code
public static String Bytes2HexString(byte[] b)    //byte转换为十六进制    {        String ret = "";        for (int i = 0; i < b.length; i++) {          String hex = Integer.toHexString(b[i]& 0xFF);          if (hex.length() == 1) {            hex = '0' + hex;          }          ret += hex.toUpperCase();        }        return ret;    }
------解决方案--------------------
Java code
public static byte uniteBytes(byte src0, byte src1)    {        byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();        _b0 = (byte)(_b0 << 4);        byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();        byte ret = (byte)(_b0 | _b1);        return ret;    }          public static byte[] HexString2Bytes(String src)    //十六进制转byte    {               byte[] tmp = src.getBytes();        byte[] ret = new byte[tmp.length/2];        for(int i=0; i<ret.length; i++){          ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);        }        return ret;      }        public static String byte2HexString(byte[] b) {        char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',                      '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};        char[] newChar = new char[b.length * 2];        for(int i = 0; i < b.length; i++) {            newChar[2 * i] = hex[(b[i] & 0xf0) >> 4];            newChar[2 * i + 1] = hex[b[i] & 0xf];        }        return new String(newChar);    }
  相关解决方案