开发者

C# Convert Integer To Hex?

开发者 https://www.devze.com 2023-02-28 00:48 出处:网络
I am using the Cosmos template to build a c# os. I need to write my own method that will convert a int value to a 2 byte use hex value. I can\'t use any prebuilt functions (like ToString(\"X\") or Str

I am using the Cosmos template to build a c# os. I need to write my own method that will convert a int value to a 2 byte use hex value. I can't use any prebuilt functions (like ToString("X") or 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.

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号