我需要将十进制更改为二进制,将每个数字保存在大小为10的数组中。
实际上,我可以简单地将十进制更改为二进制,但是我很难理解其位数。
假设int a = 3
,则其二进制形式为11
。
但是我需要将其保存为一个尺寸的维数组10
,以打印为0000000011
而不是11
。
再举一个例子,如果我输入小数87
,我的代码应为print 01010111
。
如何计算每个数字并将其保存到数组中的正确位置?
我现在无法对其进行测试,但这可能会有所帮助:
// Here there should be the necessary include to enable printing
unsigned int size = 10; // The size of the array that should store the bin output
int a = 3; // The int to be converted to bin
// A function that returns a pointer to a byte, that will be interpreted as an array
unsigned short int
*IntToBin (int input)
{
static unsigned short int output[size]; // Declaring the array to be returned by
// the function, with keyword 'static' to
// allow it to be referenced from outside
for (int i = 0; i < size; i++) {
output[i] = (input >> (size - 1 - i)) & 0x1; // Populating output array by
// bit-shifting the input int
// and doing a bitwise 'and' to
// keep only least significant
// digit
}
return output; // Returning the output array (an array is essentially a pointer,
// so this matches the function declaration)
}
// The main function, that will take care of calling the conversion function and
// printing its output
void
main ()
{
unsigned short int result[] = IntToBin (a); // Assigns the output of the conversion
// function to an array
// Prints the input and output of the conversion function
print("a = ");
print(a);
print("\na in bin = ");
for (int i = 0; i < size; i++) {
print (result[i]);
}
print("\n");
}
但是,如注释中所述,有符号的int的行为与无符号的int的行为不同。10
输出数组的长度有点奇怪。
https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句