我开发了一个将 int 转换为 32 位的函数。问题是我试图将返回的位放入 int 数组类型中,但它没有出现。我应该使用 char 数组吗?由于我需要将这些位一点一点地传递给另一个函数,所以我需要将它们存储在数组中。下面是代码:
int main()
{
int x=24; // int whose 32 bits i need
int n=32; // number of bits needed
int p=0; // starting position.
int py[32]=getBits(x,p,n);
printf("\n",py);
return 0;
}
unsigned getBits(unsigned x, unsigned p, unsigned n) {
return (x >> (p + 1 - n)) & ~(~0 << n);
}
最佳答案
这里有很多错误,比如运行时给数组赋值。
要将 32 位 int 的各个位存储到数组元素中,您可以使用如下内容。
//assumes bits has been declared as unsignef char bits[32]
void get_bits32(unsigned char * bits, unsigned int x) {
for(int i = 0; i < 32; i++)
bits[i] = (x >> i) & 1u;
}
您可以修改它以指定数组的位数或长度,如下所示。
void get_bits32(unsigned char * bits, int n, unsigned int x) {
for(int i = 0; i < n; i++)
bits[i] = (x >> i) & 1u;
}
这里使用了一个字符数组,因为您预计只有 0 或 1。
此版本将最低有效位存储在数组的位置 0 处。
要打印此内容,您必须打印数组的每个元素,例如。
for(int i = 0; i < n; i++)
printf("%d", bits[i]);
关于int 到位错误返回类型的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252150/