You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何将十六进制字符串转byte且不篡改信息,替换数组固定值

How to Convert Hex Strings to Bytes for Your Java Byte Array

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:04:06