0

I want to read an int number bit by bit from a list, for example: decimal list: [28,171,3,324,66]

first: 28 binary: 100111 second: 171 binary: 10101011 ...

I was trying to do the bitwise operation but I don't know the length of the binary(e.g. length of 100111 = 6). So I can't do the bitwise operation. Is there any way to read an arbitrary number?

4
  • Can you explain length of 100111 = 3? You can get the number of bits with sizeof(the_number) * 8. Commented May 28, 2020 at 1:40
  • Sorry, my bad, that should be 6, I will modify it. Commented May 28, 2020 at 1:41
  • @JohnnyMopp So can I do this: for (int i=0; i < sizeof(the_number) * 8; i++) { the_number << i >> sizeof(the_number)-i } Commented May 28, 2020 at 1:45
  • You can simply keep right-shifting the number until it becomes 0, then you've found the highest bit. Commented May 28, 2020 at 1:47

2 Answers 2

0

Here's a version that right shifts the number until zero and builds the buffer from right to left:

#include <stdio.h>

const char *
bitprt(unsigned int val)
{
    char *bp;
    char *rtn;
    static char buf[128 + 1];

    bp = &buf[sizeof(buf) - 1];
    *bp-- = 0;

    *bp = '0';
    rtn = bp;

    for (;  val != 0;  val >>= 1, --bp) {
        if (val & 1)
            *bp = '1';
        else
            *bp = '0';
        rtn = bp;
    }

    return rtn;
}

void
dotest(unsigned int val)
{
    const char *buf;

    buf = bitprt(val);
    printf("%20u: '%s'\n",val,buf);
}

int
main(void)
{

    dotest(28);
    dotest(171);
    dotest(3);
    dotest(324);
    dotest(66);

    return 0;
}

Here's the output of the program:

                  28: '11100'
                 171: '10101011'
                   3: '11'
                 324: '101000100'
                  66: '1000010'
Sign up to request clarification or add additional context in comments.

Comments

0

If you are trying to get bit representation from integer value, here is an example of how to do that. You have to check each bit manually, there is not built in utility to iterate through "bits".

#include <stdio.h>

int main(int argc, char const *argv[])
{
  int numbers[] = { 28, 171, 3, 324, 66 };
  int numberslength = (int) (sizeof(numbers) / sizeof(int));

  // each number
  for (int i = 0; i < numberslength; ++i)
  {
    int number = numbers[i];  // get the number
    int mask = 1;             // start at the beginning
    for (int j = 0; j < sizeof(int) * 8; ++j)
    {
      // if the number has a bitwise and in that bit, 1
      printf("%c", number & mask ? '1': '0');

      // move the mask over to the next bit
      mask <<= 1;
    }

    // separate outputs by newline
    printf("\n");
  }

  return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.