我需要编写一个函数,它接收一个类型int(十进制)的参数,并返回string包含十六进制 int 值,但格式为 0xyy。
不仅如此,我还希望答案采用 4 字节的固定格式,例如:
int b = 358;
string ans = function(b);
Run Code Online (Sandbox Code Playgroud)
在这种情况下 ans = "0x00 0x00 0x01 0x66"
int a = 3567846;
string ans = function(a);
Run Code Online (Sandbox Code Playgroud)
在这种情况下 ans = "0x00 0x36 0x70 0xE6"
这应该与您的示例相匹配:
static string Int32ToBigEndianHexByteString(Int32 i)
{
byte[] bytes = BitConverter.GetBytes(i);
string format = BitConverter.IsLittleEndian
? "0x{3:X2} 0x{2:X2} 0x{1:X2} 0x{0:X2}"
: "0x{0:X2} 0x{1:X2} 0x{2:X2} 0x{3:X2}";
return String.Format(format, bytes[0], bytes[1], bytes[2], bytes[3]);
}
Run Code Online (Sandbox Code Playgroud)