簡體   English   中英

如何在Java中將十六進制字符串轉換為字節值

[英]How to convert hex strings to byte values in Java

我有一個String數組。 我想將其轉換為字節數組。 我使用Java程序。 例如:

String str[] = {"aa", "55"};

轉換成:

byte new[] = {(byte)0xaa, (byte)0x55};

我能做什么?

String str = "Your string";

byte[] array = str.getBytes();

看一下這個樣本我猜你的意思是字符串數組實際上是一個字節的HEX表示數組,不是嗎?

如果是,那么對於每個字符串項,我將執行以下操作:

  1. 檢查字符串是否只包含2個字符
  2. 這些字符在'0'..'9'或'a'..'f'間隔(考慮他們的情況)
  3. 將每個字符轉換為相應的數字,減去代碼值'0'或'a'
  4. 構建一個字節值,其中第一個char是較高位,第二個char是較低位。 例如

     int byteVal = (firstCharNumber << 4) | secondCharNumber; 

將字符串轉換為字節數組:

byte[] theByteArray = stringToConvert.getBytes();

將字符串轉換為字節:

 String str = "aa";

 byte b = Byte.valueOf(str);

你可以嘗試類似的東西:

String s = "65";

byte value = Byte.valueOf(s);

對String數組中的所有元素使用Byte.ValueOf()方法將它們轉換為字節值。

由於十六進制字符串沒有單字節轉換的答案,這是我的:

private static byte hexStringToByte(String data) {
    return (byte) ((Character.digit(data.charAt(0), 16) << 4)
                  | Character.digit(data.charAt(1), 16));
}

樣品用法:

hexStringToByte("aa"); // 170
hexStringToByte("ff"); // 255
hexStringToByte("10"); // 16

或者你也可以嘗試Integer.parseInt(String number, int radix) imo,比其他方式更好。

// first parameter is a number represented in string
// second is the radix or the base number system to be use
Integer.parseInt("de", 16); // 222
Integer.parseInt("ad", 16); // 173
Integer.parseInt("c9", 16); // 201

還有很長的路要走:) 我不知道的方法來擺脫長期for聲明

ArrayList<Byte> bList = new ArrayList<Byte>();
for(String ss : str) {
    byte[] bArr = ss.getBytes();
    for(Byte b : bArr) {
        bList.add(b);
    }
}
//if you still need an array
byte[] bArr = new byte[bList.size()];
for(int i=0; i<bList.size(); i++) {
    bArr[i] = bList.get(i);
}
String source = "testString";
byte[] byteArray = source.getBytes(encoding); 

您可以預先對數組中的所有字符串執行相同操作。

最簡單的方法(使用Apache Common Codec):

byte[] bytes = Hex.decodeHex(str.toCharArray());
String str[] = {"aa", "55"};

byte b[] = new byte[str.length];

for (int i = 0; i < str.length; i++) {
    b[i] = (byte) Integer.parseInt(str[i], 16);
}

Integer.parseInt(string,radix)將字符串轉換為整數,radix參數指定數字系統。

如果字符串表示十六進制數,則使用16的基數。
如果字符串表示二進制數,則使用2的基數。
如果字符串表示十進制數,則使用10的基數(或省略基數參數)。

有關更多詳細信息,請查看Java文檔: https//docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt( java.lang.String,% 20int)

在這里,如果要將字符串轉換為byte []。有一個實用程序代碼:

    String[] str = result.replaceAll("\\[", "").replaceAll("\\]","").split(", ");
    byte[] dataCopy = new byte[str.length] ;
    int i=0;
    for(String s:str ) {
        dataCopy[i]=Byte.valueOf(s);
        i++;
    }
    return dataCopy;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM