为什么适可而止? (在字符数组存储一个int) [英] Why ENOUGH is enough? (storing an int in a char array)

查看:133
本文介绍了为什么适可而止? (在字符数组存储一个int)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上的(及其评论)一名http://stackoverflow.com / q /一百四十三万九千八百四十三分之八百二十五万七千七百一十四>如何以下解决方案,给出一个int转换为字符串用C

In one of the answers (and its comments) on How to convert an int to string in C the following solution is given

char str[ENOUGH];
sprintf(str, "%d", 42);

在评论中 CAF 提到 ENOUGH 可确定在编译时间:

in the comments caf mentions that ENOUGH can be determined at compile time with:

#define ENOUGH ((CHAR_BIT * sizeof(int) - 1) / 3 + 2)

我得到的 + 2 ,因为你需要能够显示减号和空结束,但什么是另一部分背后的逻辑?具体来说 CHAR_BIT

I get the + 2 because you need to be able to display the minus sign and null terminator but what is the logic behind the other part? Specifically CHAR_BIT?

推荐答案

如果 INT 类型是32位的,有多少字节,你需要重新present任何数量的(没有符号和空结束)?

If int type is 32-bit, how many bytes do you need to represent any number (without sign and null terminator)?

如果 INT 类型是32位的最大 INT 值为 2147483648 (假设补),也就是 10 位,因此 10 字节存储所需的。

If int type is 32-bit the maximum int value is 2147483648 (assuming two's complement), that is 10 digits so 10 bytes needed for storage.

要了解位在 INT 在特定平台的数量(例如, 32 在我们的例子)我们可以使用 CHAR_BIT *的sizeof(int)的== 32 。记住 CHAR_BIT 是位在C字节和的sizeof 数产生字节大小。

To know the number of bits in an int in a specific platform (e.g., 32 in our example) we can use CHAR_BIT * sizeof (int) == 32. Remember CHAR_BIT is the number of bits in a C byte and sizeof yields a size in bytes.

然后(32 - 1)/ 3 = = 10 所以 10 字节需要。你也可能不知道作者是如何找到值3?那么在日志基地 2 10 是多一点比 3

Then (32 - 1) / 3 == 10 so 10 bytes needed. You may also wonder how the author finds the value 3? Well the log base 2 of 10 is a little more than 3.

这篇关于为什么适可而止? (在字符数组存储一个int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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