获得必要的最小字节数来保持一个给定的无符号的整数 [英] Get the minimum number of bytes necessary to hold a given unsigned integer
问题描述
我需要写一系列的无符号整数到一个文件,每一个是不超过 N
在运行时确定的限制更大。为了节省空间,我要收拾他们在短短字节可能。但是,我不知道如何计算要追究他们的最小字节数,所以我只有以下,丑陋的解决方案:
I need to write a series of unsigned integers to a file, each one being no greater than a limit n
determined at runtime. To save space, I want to pack them in as little bytes as possible. However, I've no idea how to compute the minimum number of bytes necessary to hold them, so I only have the following, ugly solution:
int get_needed_bytes(uint32_t n) {
if (n < 256) return 1;
else if (n < 65536) return 2;
else if (n < 16777216) return 3;
return 4;
}
有没有更好的方法来达到同样的目的?
Is there a better way to achieve the same purpose?
推荐答案
您可以尝试沿着这些路线的东西(未经测试)。
You might try something along these lines (untested).
int GetNeededBytes(uint32_t n)
{
// Maximum number of bytes supported
int bytes = 4;
// Get mask for highest order byte
// Warning: watch for overflow here
// 4 bytes should resolve to 0xff000000
int mask = 0xff << (bytes * 8);
while (bytes > 0)
{
if (n & mask)
return bytes;
mask /= 0x100;
bytes--;
}
return 0;
}
但我不知道为什么这是一个好主意。为了读出值回来,你需要一种方法来标志有多少字节重新present下一个值。我猜想,计数值会带走大部分保存的字节数。
But I'm not sure why this is a good idea. In order to read the values back, you need a way to flag how many bytes represent the next value. I suspect that count value will take away most of the bytes you saved.
有更好的融为一体pression技术可用。
There are better compression techniques available.
这篇关于获得必要的最小字节数来保持一个给定的无符号的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!