Java中如何将十六进制字符串转byte且不篡改信息,替换数组固定值
Got it, let's break this down step by step. You want to replace those hardcoded hex values in your byte array with your string variables str1="ec" and str2="ee", while making sure Java doesn't mangle the data—here's exactly how to do it:
Step 1: Convert Hex Strings to Bytes
Java's Byte.parseByte() method is perfect for this. Since your strings are two-character hex values (which map directly to a single byte), you just need to specify the radix (base) as 16 to tell the method it's parsing hexadecimal.
This method handles signed bytes correctly too—so Byte.parseByte("ec", 16) will give you exactly the same value as (byte)0xec (which is -28 in decimal, since Java bytes are signed). No data loss or tampering here.
Step 2: Rewrite Your Byte Array Line
Now just swap out the hardcoded values with the parsed bytes:
String str1 = "ec"; String str2 = "ee"; byte[] baData = new byte[] { Byte.parseByte(str1, 16), Byte.parseByte(str2, 16) };
Quick Verification
If you want to double-check everything works as expected, you can print the values to confirm they match your original hardcoded bytes:
// Check if the converted bytes match the original hardcoded ones System.out.println(Byte.parseByte(str1, 16) == (byte)0xec); // Prints true System.out.println(Byte.parseByte(str2, 16) == (byte)0xee); // Prints true
This approach is clean, efficient, and guarantees you get the exact hex values you need in your byte array.
内容的提问来源于stack exchange,提问作者watershed

