【问题标题】:Convert int to hex format 0xyy c#将int转换为十六进制格式0xyy c#
【发布时间】:2013-01-02 11:58:22
【问题描述】:

我需要编写一个函数,它接收一个 int(十进制)类型的参数,并返回 string,其中包含十六进制的 int 值,但格式为 0xyy
不仅如此,我希望答案采用 4 字节的固定格式 例如:

int b = 358;
string ans = function(b); 

在这种情况下,ans = "0x00 0x00 0x01 0x66"

int a = 3567846; 
string ans = function(a);

在这种情况下 ans = "0x00 0x36 0x70 0xE6"

【问题讨论】:

标签: c# hex


【解决方案1】:

这应该与您的示例相符:

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]);
}

【讨论】:

  • Big/Little Endian 的出色使用! +1
【解决方案2】:

我认为你想要的格式在类似的行上

int ahex = 3567846;
byte[] inthex = BitConverter.GetBytes(ahex);
Console.WriteLine("0x"+ BitConverter.ToString(inthex).Replace("-"," 0x"));

【讨论】:

  • 很好,不知道ToString 方法。
猜你喜欢
  • 1970-01-01
  • 2010-10-15
  • 2015-09-17
  • 2015-04-15
  • 2013-05-21
  • 1970-01-01
  • 2017-07-31
  • 2013-07-20
  • 2012-06-17
相关资源
最近更新 更多