I am using the Cosmos template to build ac# 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.