如何使用宏获得存储整数值所需的最少字节?
例如,如果整数小于255,则可以在1字节中恢复,
如果大于255,则至少需要2字节。
如何编写这样的BYTES_REQUIRED(i)
宏?
For example,if the integer is less than 255,than it can be restored in 1 byte,
if it's greater than 255,it requires at lest 2 bytes.
How to write such a BYTES_REQUIRED(i)
macro?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 C99 编译器,请将以下内容强制转换为
(unsigned long long)
。您还可以(并且应该)将构造扩展到 8 或 16 字节(留作练习)
If you are using a C99 compiler make the cast below to
(unsigned long long)
.Also you can (and should) extend the construct to 8 or 16 bytes (that's left as an exercise)
这使用了一种有效的分而治之的方法:
如果您不介意消除 3 个字节的奇数情况,该情况没有与之匹配的原始类型,请执行以下操作:
请注意,这些都不会处理负数,因为它会看到符号扩展1 位作为已用空间。这需要另一个条件来解释(例如,如果为负,则否定)。
This uses an efficient divide and conquer approach:
If you don't mind eliminating the odd case of 3 bytes, which has no primitive type that matches it, do:
Be warned neither one of these handles negative numbers, since it sees the sign extended 1 bits as used space. This requires another conditional to account for (e.g. if negative, negate).
您实际上需要计算 log2(i)。对于编译器和宏支持的最大整数值,没有简单的方法可以快速、可移植地实现这一点。
选项:
1. 在循环中计算对数:
2. 使用编译器的内部函数(实际上是专用 CPU 指令)(如果可用)。对于 MSVC++:
3.使用
if
或?:
了解最大支持的整数类型的大小...其他人已经描述了此方法。You effectively need to calculate log2(i). There's no trivial way of doing that portably, quickly, for the maximum integer value supported by the compiler and with a macro.
Options:
1.Calculate the logarithm in a loop:
2.Use an intrinsic function (effectively, a dedicated CPU instruction) of the compiler, if available. For MSVC++:
3.Use
if
or?:
knowing the size of the biggest supported integer type... Others have described this method already.不幸的是,您要求使用 C 宏,因为这个 C++ 模板函数可能会有所帮助(它应该适用于您的编译器支持的任何整数类型)。
如果您不仅仅需要编译时评估,另一种应该更快的方法(因为它是无分支的)是 Alex 提到的位扫描。
Unfortunately you asked for a C macro, because this C++ templated function could have been helpful (it should work for any integer type supported by your compiler).
Another approach that should be faster (because it's branchless), if you don't just need compile-time evaluation, is the bitscan that was mentioned by Alex.