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?
-
Is this a homework task?m.edmondson– m.edmondson2011-04-23 06:40:47 +00:00Commented Apr 23, 2011 at 6:40
-
Can you post your failed method? Why can't you use the built in functions? Strange limitation unless this is homework.Oded– Oded2011-04-23 06:46:23 +00:00Commented Apr 23, 2011 at 6:46
-
No its just for fun lol but the failed method just converted each number to its hex value (Like 1 to 01 , 15 to 0F ect) but it would take for ever to do that for every number and there has to be some mathematical way to convert integers to hexGrunt– Grunt2011-04-23 06:51:49 +00:00Commented Apr 23, 2011 at 6:51
Add a comment
|
1 Answer
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.
4 Comments
m.edmondson
He says he can't use ToString (for whatever reason)
Grunt
That doesnt work with the Cosmos COmpiler I was trying to write my own method to convert int to hex but it just converts each number (Like 15 to 0F) but i cant od that for every number it would take for ever
Jon Skeet
@m.edmondson: Ah, I'd missed that bit. I'd only seen that he'd tried, but it hadn't worked.
Jon Skeet
@user721493: It would have been useful to say that you were using Cosmos to start with. Personally I've no idea what the restrictions are in Cosmos, which makes this pretty hard to answer... still, editing.