如果是 2^(N+1),我怎样才能从最终结果中得到 N?

if something is 2^(N+1), how can i get N back from the end result?

我正在使用 C# 开发 GIF 编码器,作为我正在开发的其他 GIF 相关内容的 spin-off。

在 GIF 规范中,文件的 header 中有一个 "Logical Screen Descriptor",其中之一是全局颜色 table 的大小。

根据我的理解,全局颜色 Table 是 0-256 的任何地方,以 2(N+1) 格式存储为 3 位,其中 N 是 1 到 7 之间的十进制值。

我正在创建一个函数,我可以在其中将 table 大小指定为 0-256 之间的整数,然后对此执行计算以找到 N.

比如2(7+1) = 256,请问如何从256变回7?

我花了一个多小时用铅笔和 sheet 纸试图记住我大学时如何 "balance equations" 但我似乎记不起来了...

您要找的是 logarithm, specifically the base 2, or binary logarithm。维基百科说:

It is the inverse function of the power of two function. The binary logarithm of n is the power to which the number 2 must be raised to obtain the value n. That is:

在 C# 中,您可以使用 Math.Log 来计算它。

答案是如果 a = 2n+1 那么 n = log2(a) - 1. 这是java代码:

public static void main (String[] args) throws java.lang.Exception
{
    int n = 256;
    double log = Math.log(n)/Math.log(2);
    System.out.println(log-1);
}

在线version