简体   繁体   English

如何在C#中将12位整数转换为十六进制字符串?

[英]How do I convert a 12-bit integer to a hexadecimal string in C#?

I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#. 我想将0到4096之间的数字(12位)转换为C#中的3个字符的十六进制字符串表示形式。

Example: 例:

2748 to "ABC"

尝试

2748.ToString("X")

If you want exactly 3 characters and are sure the number is in range, use: 如果您只需要3个字符并且确定该数字在范围内,请使用:

i.ToString("X3")

If you aren't sure if the number is in range, this will give you more than 3 digits. 如果不确定该数字是否在范围内,这将使您获得3位以上的数字。 You could do something like: 您可以执行以下操作:

(i % 0x1000).ToString("X3")

Use a lower case "x3" if you want lower-case letters. 如果要使用小写字母,请使用小写的“ x3”。

Note: This assumes that you're using a custom, 12-bit representation. 注意:假设您使用的是自定义的12位表示形式。 If you're just using an int/uint, then Muxa's solution is the best. 如果您只使用int / uint,那么Muxa的解决方案是最好的。

Every four bits corresponds to a hexadecimal digit. 每四个位对应一个十六进制数字。

Therefore, just match the first four digits to a letter, then >> 4 the input, and repeat. 因此,只需将前四个数字与一个字母匹配,然后将输入>> >> 4匹配,然后重复。

The easy C solution may be adaptable: 简单的C解决方案可能是适用的:

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. 我希望C#可以为这种事情提供某种库函数。 You could even use sprintf in C, and I'm sure C# has an analog to this functionality. 您甚至可以在C语言中使用sprintf,而且我确信C#具有与此功能类似的功能。

-Adam -亚当

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM