计算十六进制数的位数
我正在尝试计算十六进制数中可用的位数。例如:0x00000001
应返回计数为 8
。
谁能建议最有效的方法是什么?我尝试将其转换为 CString
并使用 'GetLength()
' 获取长度,但这似乎在这里不起作用。
编辑:抱歉,如果我忘记提及,我存储十六进制数的变量是无符号短整型。
尝试过这个:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于每个字节包含两个十六进制数字,因此尝试使用整数类型的变量
n
Since each byte contains two hexadecimal digits, try for a variable
n
of integral type如果 0x00000001 是一个字符串,那么
GetLength() - 2
应该给出 8。如果它是以不同类型存储的值(比如说 int),那么只需记住事实上,十六进制编码每 8 位需要 2 个字符来编码整个值范围 (sizeof(int) * 2
)If 0x00000001 is a string then
GetLength() - 2
should give 8. If it is a value stored in a different type (lets say int), then just simply remember the fact that hex encoding needs 2 characters per 8 bits to encode the whole value range (sizeof(int) * 2
)每 4 位有 1 个十六进制数字。
There is one hex digit per 4 bits.
十六进制数 n 中的位数为 max(1, ceil(log2(n)))。请参阅维基百科,二进制对数,了解计算 log2 的快速算法。
不过,这不会为您提供
0x00000001
的值 8,因为实际上只需要数字来表示该数字。0x00000001
和0x1
之间的区别仅是显示问题。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 between0x00000001
and0x1
is a display issue only.