简体   繁体   English

C# - 将 Int 转换为 Hex 4 字节

[英]C# - Convert Int to Hex 4 Bytes

I want to convert an int to hex 4 bytes.我想将 int 转换为 hex 4 字节。

I use this:我用这个:

int a = 50;
a.ToString("X8");

This return "00000032".这返回“00000032”。

But i want to return "0x00, 0x00, 0x00, 0x32".但我想返回“0x00、0x00、0x00、0x32”。

Thanks for help.感谢帮助。

This is an area where you need to be very careful about "endianness";这是一个你需要非常小心“字节顺序”的领域; in most simple scenarios, your best bet is to use shift operations, ie在最简单的情况下,最好的办法是使用移位操作,即

static void Main()
{
    static string ByteHex(int value) => (value & 0xFF).ToString("X2");
    int a = 50;
    Console.WriteLine("0x" + ByteHex(a >> 24));
    Console.WriteLine("0x" + ByteHex(a >> 16));
    Console.WriteLine("0x" + ByteHex(a >> 8));
    Console.WriteLine("0x" + ByteHex(a));
}

In more nuanced cases, there is a new-ish BinaryPrimitives type that is your friend:在更细微的情况下,有一个新的BinaryPrimitives类型是你的朋友:

int a = 50;
Span<byte> span = stackalloc byte[4];
BinaryPrimitives.WriteInt32BigEndian(span, a);
// now access span[0] - span[3]

This is usually preferable to BitConverter which a: is allocation-heavy, and b: is awkward re endianness (you need to flip on BitConverter.IsLittleEndian )这通常比BitConverter更可取,其中 a: 分配繁重, b: 是笨拙的重新字节序(您需要打开BitConverter.IsLittleEndian

This should do the job:这应该做的工作:

int a = 50;

string result = string.Join(", ", BitConverter.GetBytes(a).Reverse().Select(b => "0x" + b.ToString("X2")));

Console.WriteLine(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM