2016-11-08 121 views
3

当我读取git的源代码时,我很困惑这个宏。类型的十进制表示的长度的近似值

/* Approximation of the length of the decimal representation of this type. */ 
    #define decimal_length(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1) 

The code is here

但是当我尝试计算类型的十进制表示的长度的逼近,我想答案是

((int)(sizeof(x) * 8 * ln2) + 1) 

这可以写成

((int)(sizeof(x) * 2.41) + 1) 

你能告诉我为什么git通过计算长度“(sizeof(x)* 2.56 + 0.5)”而不是“(sizeof(x)* 2.41)”?
非常感谢。

+1

“为什么这样设计的东西”通常不会在StackOverflow上负责,因为只有作者才能给出确定的答案。 –

+1

我假设这是用来计算打印给定类型的有符号整数所需的最大字符数。你的推理是正确的。但只要计算在'sizeof(x)'为1,2,4或8时给出正确的答案,那么它并不重要。 –

+1

应该是'((int)(sizeof(x)* 2.41 + 1.65))'从8位到128位得到正确答案。 – user3386109

回答

3

看起来像一个烘烤的机会!下面是结果我从四个不同数量的尺寸越来越:

A = (sizeof(x) * 2.56 + 0.5) + 1 
B = (sizeof(x) * 2.41) + 1 
C = (sizeof(x) * 2.41 + 1.65) 

strlen A B C Number (bytes) 

4  4 3 4 -127 (1) 
6  6 5 6 -32767 (2) 
11  11 10 11 -2147483647 (4) 
20  21 20 20 -9223372036854775807 (8) 

荣誉给user3386109。所有这些方案试图估计最大可能长度,而不是实际长度(即,他们不关心'x'包含什么值)。以下是我用来生成上述表格的代码。我没有在我的系统中包含long long,它与long的尺寸相同。

#include <stdio.h> 
#include <string.h> 

#define decimal_length1(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1) 

#define decimal_length2(x) ((int)(sizeof(x) * 2.41) + 1) 

#define decimal_length3(x) ((int)(sizeof(x) * 2.41 + 1.65)) 

int main() { 

    char buffer[1024]; 

    char a = -127; 
    short b = -32767; 
    int c = -2147483647; 
    long int d = -9223372036854775807L; 

    printf("A = (sizeof(x) * 2.56 + 0.5) + 1\n"); 
    printf("B = (sizeof(x) * 2.41) + 1\n"); 
    printf("C = (sizeof(x) * 2.41 + 1.65)\n\n"); 

    printf("strlen\tA\tB\tC\tNumber (bytes)\n\n"); 

    sprintf(buffer, "%hhd", a); 
    printf("%lu\t%d\t%d\t%d\t%s (%lu)\n", strlen(buffer), decimal_length1(a), decimal_length2(a), decimal_length3(a), buffer, sizeof(a)); 

    sprintf(buffer, "%hd", b); 
    printf("%lu\t%d\t%d\t%d\t%s (%lu)\n", strlen(buffer), decimal_length1(b), decimal_length2(b), decimal_length3(b), buffer, sizeof(b)); 

    sprintf(buffer, "%d", c); 
    printf("%lu\t%d\t%d\t%d\t%s (%lu)\n", strlen(buffer), decimal_length1(c), decimal_length2(c), decimal_length3(c), buffer, sizeof(c)); 

    sprintf(buffer, "%ld", d); 
    printf("%lu\t%d\t%d\t%d\t%s (%lu)\n", strlen(buffer), decimal_length1(d), decimal_length2(d), decimal_length3(d), buffer, sizeof(d)); 

    return 0; 
} 
+0

非常感谢。我忽略了负数。 –