gpt4 book ai didi

c - 将二进制值存储到无符号 int 数组中

转载 作者:行者123 更新时间:2023-11-30 16:43:05 26 4
gpt4 key购买 nike

我在将二进制值存储到 unsigned int 数组中时遇到了一些麻烦。我试图将二进制表示形式作为 char 数组传递,但它并没有像我希望的那样工作。我所做的是使用 while 循环遍历 char 数组,并将每个数字分配给 unsigned int 数组的一个元素,但这就是完全错误的。我只是非常想知道如何将二进制值存储到 unsigned int 中。如何在前面显示零?我尝试将前面没有 0 的二进制值放入数组中,但这不起作用。我可以将二进制转换为 int 值,然后在打印时将其转换回来吗?

这是该函数的基本代码

void setstring(unsigned int array[10], char *bitString) {
len=strlen(bitString);
for (int i=1; i<=10; i++) {
for (int p=1; d%32!=0; d++) {
array[10-i]=bitString[len-];
}
}
}

打印只是为了打印bitString或数组,但目前根本没有打印任何内容。打印只是一个 for 循环,它迭代 unsigned int 数组。

最佳答案

您可能正在寻找一个函数来设置 unsigned char 变量的特定位。

尝试使用它来设置位

void setBit(unsigned char *target, int pos)
{
//pos must be < sizeof(unsigned char)
unsigned char mask=1<<pos;
*target = *target | mask;
}


这可以取消设置位

void unsetBit(unsigned char *target, int pos)
{
unsigned char mask=~(1<<pos);
*target = *target & mask;
}

请注意,pos0 开始。

您可以使用这些函数来显示位:

int getBit(unsigned char target, int pos)
{
target = target>>pos;
return target & 1;

}

void printBits(unsigned char target)
{
int i;
for(i=sizeof(target)*8-1; i>=0; --i)
{
printf("%d", getBit(target, i));
}
}

在这些函数中,目标变量通过引用传递。

示例:

unsigned char a=0;
setBit(&a, 0);
setBit(&a, 1);
setBit(&a, 6);
printf("\nBit pattern is: ");
printBits(a);
printf(". Value is %d.", a);

会打印

Bit pattern is: 01000011. Value is 67.

进一步

unsetBit(&a, 1);
printf("\nBit pattern is: ");
printBits(a);
printf(". Value is %d.", a);

会给

Bit pattern is: 01000001. Value is 65.

编辑:This是学习位操作的好地方。

关于c - 将二进制值存储到无符号 int 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45531597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com