Grunt
Grunt

Reputation: 173

C# Convert Integer To Hex?

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?

Upvotes: 0

Views: 1673

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503419

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.

Upvotes: 1

Related Questions