I am trying to count the number of digits that are available in a hexadecimal number. For example: 0x00000001
should return the count as 8
.
Could anyone suggest as to what is the most efficient way of doing this? I have tried converting it to a CString
and get the length using ' GetLength()
' but that doesn't seem to work here.
Edit: Sorry if I forgot to mentioned, my variable that stores the hexadecimal number is an unsigned short.
Tried this:
unsigned short number;
CString HexValue;
HexValue.Format("%.8x",number); // number = 0000000000000000, 16 0's
HexValue = "0x" + HexValue;
int length = HexValue.GetLength() - 2; // returns an 8 here
由于每个字节包含两个十六进制数字,请尝试使用整数类型的变量n
sizeof(n)*CHAR_BIT/4
如果0x00000001是一个字符串,则GetLength() - 2
应该为8。如果它是存储在不同类型中的值(假设为int),则只需记住十六进制编码需要每8位2个字符来对整个整数进行编码值范围( sizeof(int) * 2
)
There is one hex digit per 4 bits.
std::cout << sizeof(unsigned short) * CHAR_BIT / 4 << "\n";
std::cout << sizeof(unsigned short) * CHAR_BIS % 4 << " LEFTOVER PARTIAL DIGITS\n";
The number of digits in a hexadecimal number n is max(1, ceil(log2( n ))). See Wikipedia, Binary logarithm for a fast algorithm to compute log2.
That won't give you the value 8 for 0x00000001
, though, since there's actually only digit needed to represent that number. The difference between 0x00000001
and 0x1
is a display issue only.
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.