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"
尝试
2748.ToString("X")
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.
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.
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
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.