Java中byte與(16進制)字符串的互相轉換

java中byte用二進制表示佔用8位,而咱們知道16進制的每一個字符須要用4位二進制位來表示,因此咱們就能夠把每一個byte轉換成兩個相應的16進制字符,即把byte的高4位和低4位分別轉換成相應的16進制字符H和L,並組合起來獲得byte轉換到16進制字符串的結果new String(H) + new String(L)。即byte用十六進制表示只佔2位。java

同理,相反的轉換也是將兩個16進制字符轉換成一個byte,原理同上。數組

根據以上原理,咱們就能夠將byte[] 數組轉換爲16進制字符串了,固然也能夠將16進制字符串轉換爲byte[]數組了。app

先說一下二進制補碼ui

左移是在後面補0
右移是在前面邊補1或0,看最高位是0仍是1,是0就補0,是1就補1.
左移始終是在右邊補,不會產生符號問題,而右移會,因此要判斷。編碼

    /**spa

Java代碼       收藏代碼   
  1.  * Convert byte[] to hex string.這裏咱們能夠將byte轉換成int,而後利用Integer.toHexString(int)來轉換成16進制字符串。  
  2.  * @param src byte[] data  
  3.  * @return  hex string  
  4.  */     
  5. public static String bytesToHexString(byte[] src){  
  6.     StringBuilder stringBuilder = new StringBuilder("");  
  7.     if (src == null || src.length <= 0) {  
  8.         return null;  
  9.     }  
  10.     for (int i = 0; i < src.length; i++) {  
  11.         int v = src[i] & 0xFF;  
  12.         String hv = Integer.toHexString(v);  
  13.         if (hv.length() < 2) {  
  14.             stringBuilder.append(0);  
  15.         }  
  16.         stringBuilder.append(hv);  
  17.     }  
  18.     return stringBuilder.toString();  
  19. }  
  20. /** 
  21.  * Convert hex string to byte[] 
  22.  * @param hexString the hex string 
  23.  * @return byte[] 
  24.  */  
  25. public static byte[] hexStringToBytes(String hexString) {  
  26.     if (hexString == null || hexString.equals("")) {  
  27.         return null;  
  28.     }  
  29.     hexString = hexString.toUpperCase();  
  30.     int length = hexString.length() / 2;  
  31.     char[] hexChars = hexString.toCharArray();  
  32.     byte[] d = new byte[length];  
  33.     for (int i = 0; i < length; i++) {  
  34.         int pos = i * 2;  
  35.         d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
  36.     }  
  37.     return d;  
  38. }  
  39. /** 
  40.  * Convert char to byte 
  41.  * @param c char 
  42.  * @return byte 
  43.  */  
  44.  private byte charToByte(char c) {  
  45.     return (byte) "0123456789ABCDEF".indexOf(c);  
  46. }  
    Java代碼       收藏代碼   
  1. //將指定byte數組以16進制的形式打印到控制檯  
  2. public static void printHexString( byte[] b) {    
  3.    for (int i = 0; i < b.length; i++) {   
  4.      String hex = Integer.toHexString(b[i] & 0xFF);   
  5.      if (hex.length() == 1) {   
  6.        hex = '0' + hex;   
  7.      }   
  8.      System.out.print(hex.toUpperCase() );   
  9.    }   
  10.   
  11. }  

 

java中byte轉換int時爲什麼與0xff進行與運算.net

在剖析該問題前請看以下代碼code

Java代碼       收藏代碼   
  1. public static String bytes2HexString(byte[] b) {  
  2.   String ret = "";  
  3.   for (int i = 0; i < b.length; i++) {  
  4.    String hex = Integer.toHexString(b[ i ] & 0xFF);  
  5.    if (hex.length() == 1) {  
  6.     hex = '0' + hex;  
  7.    }  
  8.    ret += hex.toUpperCase();  
  9.   }  
  10.   return ret;  
  11. }  

  上面是將byte[]轉化十六進制的字符串,注意這裏b[ i ] & 0xFF將一個byte和 0xFF進行了與運算,而後使用Integer.toHexString取得了十六進制字符串,能夠看出 b[ i ] & 0xFF運算後得出的仍然是個int,那麼爲什麼要和 0xFF進行與運算呢?直接 Integer.toHexString(b[ i ]);,將byte強轉爲int不行嗎?答案是不行的.
其緣由在於: 1.byte的大小爲8bits而int的大小爲32bits 2.java的二進制採用的是補碼(參考上面)形式。utf-8

其餘方法字符串

 

toHexString
public static String toHexString(int i)以十六進制的無符號整數形式返回一個整數參數的字符串表示形式。
若是參數爲負,那麼無符號整數值爲參數加上 232;不然等於該參數。將該值轉換爲十六進制(基數 16)的無前導 0 的 ASCII 數字字符串。若是無符號數的大小值爲零,則用一個零字符 '0' ('\u0030') 表示它;不然,無符號數大小的表示形式中的第一個字符將不是零字符。用如下字符做爲十六進制數字:
0123456789abcdef
這些字符的範圍是從 '\u0030' 到 '\u0039' 和從 '\u0061' 到 '\u0066'。若是但願獲得大寫字母,能夠在結果上調用 String.toUpperCase() 方法:
Integer.toHexString(n).toUpperCase()
參數:
i - 要轉換成字符串的整數。
返回:
用十六進制(基數 16)參數表示的無符號整數值的字符串表示形式。
// 轉化字符串爲十六進制編碼
public static String toHexString(String s)
{
String str="";
for (int i=0;i<s.length();i++)
{
int ch = (int)s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
// 轉化十六進制編碼爲字符串
public static String toStringHex(String s)
{
byte[] baKeyword = new byte[s.length()/2];
for(int i = 0; i < baKeyword.length; i++)
{
try
{
baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16));
}
catch(Exception e)
{
e.printStackTrace();
}
}
try
{
s = new String(baKeyword, "utf-8");//UTF-16le:Not
}
catch (Exception e1)
{
e1.printStackTrace();
}
return s;
}
// 轉化十六進制編碼爲字符串
public static String toStringHex(String s)
{
byte[] baKeyword = new byte[s.length()/2];
for(int i = 0; i < baKeyword.length; i++)
{
try
{
baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16));
}
catch(Exception e)
{
e.printStackTrace();
}
}
try
{
s = new String(baKeyword, "utf-8");//UTF-16le:Not
}
catch (Exception e1)
{
e1.printStackTrace();
}
return s;
}
public static void main(String[] args) {
System.out.println(encode("中文"));
System.out.println(decode(encode("中文")));
}
/*
* 16進制數字字符集
*/
private static String hexString="0123456789ABCDEF";
/*
* 將字符串編碼成16進制數字,適用於全部字符(包括中文)
*/
public static String encode(String str)
{
//根據默認編碼獲取字節數組
byte[] bytes=str.getBytes();
StringBuilder sb=new StringBuilder(bytes.length*2);
//將字節數組中每一個字節拆解成2位16進制整數
for(int i=0;i<bytes.length;i++)
{
sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
}
return sb.toString();
}
/*
* 將16進制數字解碼成字符串,適用於全部字符(包括中文)
*/
public static String decode(String bytes)
{
ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2);
//將每2位16進制整數組裝成一個字節
for(int i=0;i<bytes.length();i+=2)
baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1))));
return new String(baos.toByteArray());
}

第二種方法: 將指定byte數組以16進制的形式打印到控制檯

 

package com.nantian.iclient.atm.sdb; 

 

public class Util { 

public Util() { 

 

/** 

將指定byte數組以16進制的形式打印到控制檯 

* @param hint String 

* @param b byte[] 

* @return void 

*/ 

public static void printHexString(String hint, byte[] b) { 

System.out.print(hint); 

for (int i = 0; i < b.length; i++) { 

String hex = Integer.toHexString(b[i] & 0xFF); 

if (hex.length() == 1) { 

hex = '0' + hex; 

System.out.print(hex.toUpperCase() + " "); 

System.out.println(""); 

 

/** 

* @param b byte[] 

* @return String 

*/ 

public static String Bytes2HexString(byte[] b) { 

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; 

 

/** 

將兩個ASCII字符合成一個字節; 

如:"EF"--> 0xEF 

* @param src0 byte 

* @param src1 byte 

* @return byte 

*/ 

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; 

 

/** 

將指定字符串src,以每兩個字符分割轉換爲16進制形式 

如:"2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF, 0xD9} 

* @param src String 

* @return byte[] 

*/ 

public static byte[] HexString2Bytes(String src){ 

byte[] ret = new byte[8]; 

byte[] tmp = src.getBytes(); 

for(int i=0; i<8; i++){ 

ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]); 

return ret; 

 

相關文章
相關標籤/搜索