Reputation: 14352
I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#.
Example:
2748 to "ABC"
Upvotes: 1
Views: 3907
Reputation: 124696
If you want exactly 3 characters and are sure the number is in range, use:
i.ToString("X3")
If you aren't sure if the number is in range, this will give you more than 3 digits. You could do something like:
(i % 0x1000).ToString("X3")
Use a lower case "x3" if you want lower-case letters.
Upvotes: 2
Reputation: 93565
The easy C solution may be adaptable:
char hexCharacters[17] = "0123456789ABCDEF";
void toHex(char * outputString, long input)
{
outputString[0] = hexCharacters[(input >> 8) & 0x0F];
outputString[1] = hexCharacters[(input >> 4) & 0x0F];
outputString[2] = hexCharacters[input & 0x0F];
}
You could also do it in a loop, but this is pretty straightforward, and loop has pretty high overhead for only three conversions.
I expect C# has a library function of some sort for this sort of thing, though. You could even use sprintf in C, and I'm sure C# has an analog to this functionality.
-Adam
Upvotes: 1
Reputation: 10794
Note: This assumes that you're using a custom, 12-bit representation. If you're just using an int/uint, then Muxa's solution is the best.
Every four bits corresponds to a hexadecimal digit.
Therefore, just match the first four digits to a letter, then >> 4 the input, and repeat.
Upvotes: 1