简体   繁体   English

在 C# 中转换十六进制值

[英]Convert hex value in C#

I am trying to display a two digit hex value into 16bit hex value.我正在尝试将两位十六进制值显示为 16 位十六进制值。 ie value =81 into 0x0000000000000081 .即值 =81 到 0x0000000000000081 。 I have done the following code :我已经完成了以下代码:

public long GetHexNumber(long d)
    {

        return long.Parse(d.ToString("X"), System.Globalization.NumberStyles.HexNumber);

    }

but the above code returns the same hex value ie 81 .但上面的代码返回相同的十六进制值,即 81 。 Kindly help请帮忙

Use Int64.ToString() like this:像这样使用Int64.ToString()

    public string GetHexNumber(long d)
    {
        return d.ToString("X16");
    }

X ... for converting to hexString X ... 用于转换为 hexString

16... for converting it to 16 digit string 16...用于将其转换为 16 位字符串

If you want it to have a leading "0x" change it to:如果您希望它具有前导“0x”,请将其更改为:

    return "0x" + d.ToString("X16");

Let's start by providing a good test example, we want让我们从提供一个很好的测试示例开始,我们想要

  1. Having an integer (eg 81 )有一个整数(例如81
  2. Treat is as if it's not decimal , but hexadecimal : 0x81 (we mechanically add 0x )对待就好像它不是十进制,而是十六进制0x81 (我们机械地添加0x
  3. Obtain its value ( 0x81 == 129 )获取它的值( 0x81 == 129

Something like this:像这样的东西:

 Value -> 0xValue 

If it's your case, the solution can be如果这是你的情况,解决方案可以是

 // static: we don't have any need in "this" instance
 public static long GetHexNumber(long value) {
   return Convert.ToInt64(value.ToString(), 16);
 } 

Test测试

 long test = 81;

 Console.WriteLine(81);
 // C# 6.0+ string interpolating
 // if don't use C# 6.0, put it as formatting: 
 // Console.WriteLine("{0:X16}", GetHexNumber(test)); 
 Console.WriteLine($"{GetHexNumber(test):X16}");

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

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