简体   繁体   English

C#将整数转换为十六进制?

[英]C# Convert Integer To Hex?

I am using the Cosmos template to build ac# os. 我正在使用Cosmos模板来构建ac#os。 I need to write my own method that will convert a int value to a 2 byte use hex value. 我需要编写自己的方法,该方法会将int值转换为2字节的use hex值。 I can't use any prebuilt functions (like ToString("X") or String.Format ). 我不能使用任何预建函数(例如ToString("X")String.Format )。 I tried writting a method but it failed. 我尝试编写一种方法,但是失败了。 Any code, ideas, suggestions, or tutorials? 有任何代码,想法,建议或教程吗?

EDIT: Okay, now we know you're working in Cosmos, I have two suggestions. 编辑:好的,现在我们知道您在Cosmos工作,我有两个建议。

First: build it yourself: 首先:自己构建:

static readonly string Digits = "0123456789ABCDEF";

static string ToHex(byte b)
{
    char[] chars = new char[2];
    chars[0] = Digits[b / 16];
    chars[1] = Digits[b % 16];
    return new string(chars);
}

Note the parameter type of byte rather than int , to enforce it to be a single byte value, converted to a two-character hex string. 请注意, byte的参数类型而不是int ,以将其强制为单字节值,并转换为两个字符的十六进制字符串。

Second: use a lookup table: 第二:使用查找表:

static readonly string[] HexValues = { "00", "01", "02", "03", ... };

static string ToHex(byte b)
{
    return HexValues[b];
}

You could combine the two approaches, of course, using the first (relatively slow) approach to generate the lookup table. 当然,您可以将两种方法结合起来,使用第一种(相对较慢)的方法来生成查找表。

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

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