简体   繁体   English

在C#中将十六进制数转换为2字节字符串表示法

[英]Convert Hex Number into 2 Byte String Notation in C#

I am looking for the simplest way to achieve this : 我正在寻找实现这一目标的最简单方法:

num = 2376.75 => 0949 ( hex conversion of rounded off of 2376.5 to 2377).Num could be negative num ber as well. num = 2376.75 => 0949(十六进制转换为2376.5到2377的四舍五入)。Num也可以是负数。

I have very ugly code to do this which luckily works for me : 我很丑陋的代码来做到这一点,幸运的是对我来说:

 val1 = 2376.75
    int val = Convert.ToInt16( Math.Round(val1));
    valStringLsb = ((byte)val ).ToString("X");
     if (valStringLsb.Length == 1)
    {

      valStringLsb = "0" + valStringLsb;
    }

    string valStringmsb = ((byte)(si >> 8)).ToString("X");
    int k = valStringmsb.Length;
    if (k == 1)
    {
       valStringmsb = "0" + valStringmsb;
    }
    else
    {

    valStringmsb = ((byte)(val >> 8)).ToString("X").Equals("0") ? "00" : (((byte)(val >> 8)).ToString("X")); 
    }

    valString += (valStringLsb + valStringmsb);

Is there any simple way or API to achieve this? 有没有简单的方法或API可以实现这一目标? The reason i want to do this is I want 0949 value not 949 value for 2377. 我要执行此操作的原因是我希望0949值而不是2377的949值。

If you want to have simplicity you could use this: 如果您想简单起见,可以使用以下方法:

Func<int, string> DecimalToHex = new Func<int, string>((input) => 
{
    return Convert.ToString(input, 16).PadLeft(4, '0');
});

The important part is the Convert so you don't have to use a Func<> method. 重要的部分是Convert因此您不必使用Func<>方法。 If you want to use this approach, then you will have to supply your rounded number. 如果要使用此方法,则必须提供四舍五入的数字。 You can not supply a double into this function directly. 您不能直接在此函数中提供double。

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

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