可包含整数值的最小字节数 [英] Minimum number of bytes that can contain an integer value

查看:167
本文介绍了可包含整数值的最小字节数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个整数值,我需要一些方法来找出存储该值所需的最小字节数。该值可以是有符号或无符号,最多为64位。还要考虑签名整数的符号位。

Given an integer value, I need some way to find out the minimum number of bytes needed to store the value. The value may be signed or unsigned, up to 64-bit. Also take the sign bit into account for signed integers.

例如:

                          8     requires 1 byte at minimum
               unsigned 255     requires 1 byte at minimum
                 signed 255     requires 2 bytes at minimum
                       4351     requires 2 bytes at minimum
                -4294967296     requires 5 bytes at minimum
unsigned 0xFFFFFFFFFFFFFFFF     requires 8 bytes at minimum

我能想到一个快速的使用许多if语句解决这个问题的方法很多,但可能有更好的方法(例如更简单,更聪明,更快)。您可以假设一个方法带有签名 int(长值,bool签名)或两个方法 int(long value) (用于签名)和 int(ulong值)(对于无符号)。

I can think of a quick-and-dirty way to solve this, using many if-statements, but there might be better (e.g. simpler, cleverer, faster) ways to do this. You may either assume a method with signature int (long value, bool signed) or two methods int (long value) (for signed) and int (ulong value) (for unsigned).

推荐答案

让我试一试自己的问题。据我所知,这是一个正确的解决方案,但它在速度,简洁性方面可能不是最佳的:

Let me give it a go at my own question. As far as I can tell, this is a correct solution, but it may not be optimal in speed, conciseness:

public static int GetMinByteSize(long value, bool signed)
{
    ulong v = (ulong)value;
    // Invert the value when it is negative.
    if (signed && value < 0)
        v = ~v;
    // The minimum length is 1.
    int length = 1;
    // Is there any bit set in the upper half?
    // Move them to the lower half and try again.
    if ((v & 0xFFFFFFFF00000000) != 0)
    {
        length += 4;
        v >>= 32;
    }
    if ((v & 0xFFFF0000) != 0)
    {
        length += 2;
        v >>= 16;
    }
    if ((v & 0xFF00) != 0)
    {
        length += 1;
        v >>= 8;
    }
    // We have at most 8 bits left.
    // Is the most significant bit set (or cleared for a negative number),
    // then we need an extra byte for the sign bit.
    if (signed && (v & 0x80) != 0)
        length++;
    return length;
}

这篇关于可包含整数值的最小字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆