简体   繁体   English

C: 获取整数位

[英]C: get the bits of an integer

I have a program that will take two 4-byte integers as input and I need to store these into integer arrays like so...我有一个程序,它将接受两个 4 字节整数作为输入,我需要将它们存储到整数数组中,就像这样......

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[]) {
    int vals1[32], vals2[32];
    int num1 = atoi(argv[1]);
    int num2 = atoi(argv[2]);

    // so argv[1] might be 47 and I would want to set the values of the vals1 array to reflect that in binary form
}

Any suggestions?有什么建议?

First task would be to convert a char * to an int , which you said you can.第一项任务是将char *转换为int ,您说可以。 So here comes the next part ie getting the binary representation.所以这里是下一部分,即获取二进制表示。 For getting the binary representation of any data type, usage of Shift Operator is one of the best ways.要获得任何数据类型的二进制表示,使用Shift 运算符是最好的方法之一。 And you can get it by performing shift on the data type and then performing Bitwise AND ie & with 1 .您可以通过对数据类型执行移位然后执行按位 AND ie & with 1来获得它。 For example, if n is an integer例如,如果n是一个整数

int n = 47;
for (int i = 0; i < 32; i++)
{
   /* It's going to print the values of bits starting from least significant. */
   printf("Bit%d = %d\r\n", i, (unsigned int)((n >> i) & 1));
}

So, using shift operator, solution to your problem would be something like因此,使用移位运算符,您的问题的解决方案将类似于

void fun(int n1, int n2)
{
    int i, argv1[32], argv2[32];

    for (i = 0; i < 32; i++)
    {
        argv1[i] = ((unsigned int)n1 >> i) & 1;
        argv2[i] = ((unsigned int)n2 >> i) & 1;
    }
}

You have to be careful about the bit order ie which bit are being stored at which of the array index.您必须注意位顺序,即哪个位存储在数组索引的哪个位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM