简体   繁体   中英

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...

#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. 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. And you can get it by performing shift on the data type and then performing Bitwise AND ie & with 1 . For example, if n is an integer

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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