问题描述
在提及的问题,答案
:我可以用这个方法,使该解决方案将是平台独立的。
In reference to question and the answerhere: Can I use this method so that the solution will be platform independent.
char *buff = (char*) malloc(sizeof(unsigned long)*8);
sprintf(buff, "%lu", unsigned_long_variable);
在这里,我得到它必将类似于无符号长变量缓冲区长度的值。难道这种做法是否正确?
Here I am getting the value of buffer length as it will similar to unsigned long variable. Is this approach correct?
推荐答案
您想知道需要多少个字符重新present最大可能的无符号长
。是否正确?
You want to know how many characters are needed to represent the largest possible unsigned long
. Correct?
为此,您要计算最大可能的无符号长
:
To that end, you are trying to calculate the largest possible unsigned long
:
sizeof(unsigned long)*8
这是在几个方面有缺陷。其一,的sizeof
字符
的回报倍数,不必是8位。你应该 CHAR_BIT
乘(从<&limits.h中GT;
)代替。但是,即使是没有必要的,因为这非常相同的标题已经不提供尽可能大的价值 - UCHAR_MAX
That is faulty in several ways. For one, sizeof
returns multiples of char
, which need not be 8 bit. You should multiply with CHAR_BIT
(from <limits.h>
) instead. But even that is not necessary, because that very same header already does provide the largest possible value -- UCHAR_MAX
.
然后,你犯了一个错误:你的计算给出的大小的整数的重新presentation无符号长
的在位的。你什么希望的是字符串的再presentation中的字符大小的。这可以用 LOG10()
函数来实现(从&LT;文件math.h&GT;
)
Then you're making a mistake: Your calculation gives the size of the integer representation of unsigned long
in bits. What you want is the size of the string representation in characters. This can be achieved with the log10()
function (from <math.h>
):
log10( UCHAR_MAX )
这会给你一个双击
值,指示的(十进制)的位数UCHAR_MAX
。这将是一小部分,它需要四舍五入的最多的(1)( CEIL()
为您完成此)。
This will give you a double
value that indicates the number of (decimal) digits in UCHAR_MAX
. It will be a fraction, which you need to round up (1) (ceil()
does this for you).
因此:
#include <math.h>
#include <stdlib.h>
#include <limits.h>
int main()
{
char * buff = malloc( ceil( log10( UCHAR_MAX ) ) + 1 );
//...
}
所有的一切,这是很狡猾的(我做的两个的错误,在写这一点,可耻的是我 - 如果你使用你这个,羞愧时犯错误)。它要求的snprintf(NULL,...)
能为你做更容易,通过Q&放指示的东西使用的数学库; A链接到您
All in all, this is quite dodgy (I made two mistakes while writing this out, shame on me -- if you make mistakes when using this, shame on you). And it requires the use of the math library for something that snprintf( NULL, ... )
can do for you more easily, as indicated by the Q&A you linked to.
(1): LOG10(9999)
给 3.9999565 ...
为四位数字号码。
(1): log10( 9999 )
gives 3.9999565...
for the four-digit number.
这篇关于缓冲区大小转换无符号长串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!