嗨,我对编码很陌生,我真的需要帮助。 基本上我有一个十进制值,并将其转换为二进制值。 使用此方法
long decimalToBinary(long n)
{
int remainder;
long binary = 0, i = 1;
while(n != 0)
{
remainder = n%2;
n = n/2;
binary= binary + (remainder*i);
i = i*10;
}
return binary;
}
我想将二进制文件的每个字符放入数组内它自己的空间中。但是,我似乎无法将返回值中的数字保存在字符串数组中。我认为这与将长字符转换为字符串有关,但我可能是错的!这是我到目前为止所拥有的。 我不想使用 sprintf();我不想打印该值,我只想将值存储在其中,以便 if 条件可以读取它。任何帮助将不胜感激!
int decimalG = 24;
long binaryG = decimalToBinary(decimalG);
char myStringG[8] = {binaryG};
for( int i = 0; i<8; i++)
{
if (myStringG[i] == '1' )
{
T1();
}
else
{
T0();
}
}
在本例中,由于十进制为 24,二进制为 11000,因此应执行函数 T1(); 2 次,T0() 6 次。但它并没有这样做,我似乎找不到将保存的值存储在数组中的答案。
*Ps Itoa();功能也不是一个选项。提前致谢! :)
最佳答案
由于帖子被标记为 arm
,因此使用 malloc()
可能不是最好的方法,尽管是最简单的方法。如果您坚持使用数组:
#include <stdio.h>
#include <stdlib.h>
int decimalToBinary(long n, char out[], int len)
{
long remainder;
// C arrays are zero based
len--;
// TODO: check if the input is reasonable
while (n != 0) {
// pick a bit
remainder = n % 2;
// shift n one bit to the right
// It is the same as n = n/2 but
// is more telling of what you are doing:
// shifting the whole thing to the right
// and drop the least significant bit
n >>= 1;
// Check boundaries! Always!
if (len < 0) {
// return zero for "Fail"
return 0;
}
// doing the following four things at once:
// cast remainder to char
// add the numerical value of the digit "0"
// put it into the array at place len
// decrement len
out[len--] = (char) remainder + '0';
}
// return non-zero value for "All OK"
return 1;
}
// I don't know what you do here, but it
// doesn't matter at all for this example
void T0()
{
fputc('0', stdout);
}
void T1()
{
fputc('1', stdout);
}
int main()
{
// your input
int decimalG = 24;
// an array able to hold 8 (eight) elements of type char
char myStringG[8];
// call decimalToBinary with the number, the array and
// the length of that array
if (!decimalToBinary(decimalG, myStringG, 8)) {
fprintf(stderr, "decimalToBinary failed\n");
exit(EXIT_FAILURE);
}
// Print the whole array
// How to get rid of the leading zeros is left to you
for (int i = 0; i < 8; i++) {
if (myStringG[i] == '1') {
T1();
} else {
T0();
}
}
// just for the optics
fputc('\n', stdout);
exit(EXIT_SUCCESS);
}
计算所需的长度很棘手,但如果您知道 Micro 使用的 long
的大小(现在为 8、16、32,甚至 64 位),您可以将其作为最大大小对于数组。保留前导零,但这应该不是问题,不是吗?
关于c - 需要使用C将int转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39112255/