如何将8个Byte变量的十六进制值拼接为单个字符串?
字节十六进制值拼接为单个字符串的实现方案
给定8个Byte变量:
Byte7 = 0 dez, hex: 00
Byte6 = 2 dez, hex: 02
Byte5 = 32 dez, hex: 20
Byte4 = 33 dez, hex: 21
Byte3 = 17 dez, hex: 11
Byte2 = 37 dez, hex: 25
Byte1 = 3 dez, hex: 03
Byte0 = 88 dez, hex: 58
需要将它们的十六进制值按Byte7到Byte0的顺序拼接为单个字符串,期望结果:0002202111250358
Python 实现
byte7 = 0 byte6 = 2 byte5 = 32 byte4 = 33 byte3 = 17 byte2 = 37 byte1 = 3 byte0 = 88 # 按Byte7到Byte0的顺序,格式化为两位小写十六进制字符串 result = f"{byte7:02x}{byte6:02x}{byte5:02x}{byte4:02x}{byte3:02x}{byte2:02x}{byte1:02x}{byte0:02x}" print(result) # 输出: 0002202111250358
C# 实现
byte byte7 = 0; byte byte6 = 2; byte byte5 = 32; byte byte4 = 33; byte byte3 = 17; byte byte2 = 37; byte byte1 = 3; byte byte0 = 88; // 按顺序拼接两位大写十六进制字符串(小写用"x2") string result = string.Concat( byte7.ToString("X2"), byte6.ToString("X2"), byte5.ToString("X2"), byte4.ToString("X2"), byte3.ToString("X2"), byte2.ToString("X2"), byte1.ToString("X2"), byte0.ToString("X2") ); Console.WriteLine(result); // 输出: 0002202111250358
Java 实现
public class ByteHexConcat { public static void main(String[] args) { byte byte7 = 0; byte byte6 = 2; byte byte5 = 32; byte byte4 = 33; byte byte3 = 17; byte byte2 = 37; byte byte1 = 3; byte byte0 = 88; StringBuilder sb = new StringBuilder(); // 按Byte7到Byte0顺序拼接,& 0xFF处理byte的符号位问题 sb.append(String.format("%02x", byte7 & 0xFF)) .append(String.format("%02x", byte6 & 0xFF)) .append(String.format("%02x", byte5 & 0xFF)) .append(String.format("%02x", byte4 & 0xFF)) .append(String.format("%02x", byte3 & 0xFF)) .append(String.format("%02x", byte2 & 0xFF)) .append(String.format("%02x", byte1 & 0xFF)) .append(String.format("%02x", byte0 & 0xFF)); String result = sb.toString(); System.out.println(result); // 输出: 0002202111250358 } }
核心逻辑总结
不管使用哪种编程语言,核心步骤都是:
- 将每个Byte变量转换为两位十六进制字符串(数值小于16时自动补前导零);
- 严格按照Byte7 → Byte6 → Byte5 → ... → Byte0的顺序拼接所有十六进制字符串,得到最终结果。
内容的提问来源于stack exchange,提问作者Markus.H1
相关产品推荐
相关产品推荐

