将八个字节转换成一个字符串



我有八个字节的变量:

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

问题:我怎么能把所有这些放在一起,只生成一个字符串,然后每个字节都有十六进制值?结果字符串应该是这样的:0002202111250358

感谢

这是一种方法:

Console.WriteLine($"{Byte7:X2}{Byte6:X2}{Byte5:X2}{Byte4:X2}{Byte3:X2}{Byte2:X2}{Byte1:X2}{Byte0:X2}");

它使用字符串格式化程序X2将字节格式化为2位十六进制。

如果你想将其推广到任何数量的字节(在合理的范围内(,你可以写一个助手方法来做到这一点:

public static string BytesToString(params byte[] bytes)
{
return string.Concat(bytes.Select(b => b.ToString("X2")));
}

然后你可以用任意数量的字节调用:

public static void Main()
{
byte Byte7 = 0;
byte Byte6 = 2;
byte Byte5 = 32;
byte Byte4 = 33;
byte Byte3 = 17;
byte Byte2 = 37;
byte Byte1 = 3;
byte Byte0 = 88;
var result = BytesToString(Byte7, Byte6, Byte5, Byte4, Byte3, Byte2, Byte1, Byte0);
Console.WriteLine(result); // 0002202111250358
}

此外,如果您希望以bit深奥的方式实现目标,您可以使用逐位or(|)操作将单个字节组合为无符号64位整数。这对于C/C++等低级编程语言或C#等一些中间编程语言来说相当容易(但对于Java则不然!(。

使用好的旧javascript,它可以在arghhh!this is the worst nightmare:)之间进行测量。

我分享这个片段只是为了教育目的,但当然,如果你喜欢and/or crazy enough :D,欢迎你采用这个片段提供的解决方案。。。

谢谢你,玩得开心。

// <!> `n >>> 0` triple right shift enforces to be unsigned 32bit integer
// <!> unsigned 32 bit versions of the bytes
const b7 =  0 >>> 0; // dez, hex: 00
const b6 =  2 >>> 0; // dez, hex: 02
const b5 = 32 >>> 0; // dez, hex: 20
const b4 = 33 >>> 0; // dez, hex: 21
const b3 = 17 >>> 0; // dez, hex: 11
const b2 = 37 >>> 0; // dez, hex: 25
const b1 =  3 >>> 0; // dez, hex: 03
const b0 = 88 >>> 0; // dez, hex: 58
// combined the high part of the bytes as u32 
const high = (
b7 << 24
| b6 << 16
| b5 <<  8
| b4 <<  0
) >>> 0;
// combined the low part of the bytes as u32 
const low = (
b3 << 24
| b2 << 16
| b1 <<  8
| b0 <<  0
) >>> 0;
// BigInt (unsigned) version of the low
const u64low = BigInt.asUintN(64, BigInt(low));
// BigInt (unsigned) version of the high
const u64high = BigInt.asUintN(64, BigInt(high));
// BigInt (unsigned) version of the combined high and low
// <!> Multiplyting u64 with 0x100000000n is the same as shifting the bits 32 times to the left
// <!> BigInt can not operate bitwise operators with good old JS
const combined = BigInt.asUintN(64, u64low + u64high * 0x100000000n);
// Hex string of the result
const resultStr = `0x${combined.toString(16).padStart(16, '0')}`;
// Let's show it in our esoteric div :)
document.querySelector('#esoteric').innerHTML = resultStr;
#esoteric {
background: #eee;
color: #333;
border: 0.0625rem solid #333;
border-radius: 0.25rem;
padding: 0.625rem;
}
<div id="esoteric"></div>

相关内容

最新更新