4

I have a binary number 1011011, how can I loop through all these binary digits one after the other ?

I know how to do this for decimal integers by using modulo and division.

Attilah
  • 17,632
  • 38
  • 139
  • 202

9 Answers9

6
int n = 0x5b; // 1011011

Really you should just do this, hexadecimal in general is much better representation:

printf("%x", n); // this prints "5b"

To get it in binary, (with emphasis on easy understanding) try something like this:

printf("%s", "0b"); // common prefix to denote that binary follows
bool leading = true; // we're processing leading zeroes
// starting with the most significant bit to the least
for (int i = sizeof(n) * CHAR_BIT - 1; i >= 0; --i) {
    int bit = (n >> i) & 1;
    leading |= bit; // if the bit is 1, we are no longer reading leading zeroes
    if (!leading)
        printf("%d", bit);
}
if (leading) // all zero, so just print 0
    printf("0");

// at this point, for n = 0x5b, we'll have printed 0b1011011
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
  • Note in advance: You want to include limits.h, stdbool.h (requires C99), stdio.h if you try to build this. If these aren't available for whatever reason, let me know and I'll modify the code to conform to your respective system. – Matt Joiner Nov 07 '10 at 09:11
  • 1
    Note that you can just say printf("0b"); no need for the %s and string argument. – Nathan S. Jan 17 '11 at 06:37
3

You can use modulo and division by 2 exactly like you would in base 10. You can also use binary operators, but if you already know how to do that in base 10, it would be easier if you just used division and modulo

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
3

Expanding on Frédéric and Gabi's answers, all you need to do is realise that the rules in base 2 are no different to in base 10 - you just need to do your division and modulus with a divisor 2 instead of 10.

The next step is simply to use number >> 1 instead of number / 2 and number & 0x1 instead of number % 2 to improve performance. Mind you, with modern optimising compilers there's probably no difference...

Mac
  • 14,615
  • 9
  • 62
  • 80
  • There is a difference if `number` is signed. The compiler has to go to extra trouble to meet C's inept definition of division (`(-3)/2==-1`, not `-2` like it should). Of course in many cases you should fix this just by using unsigned types rather than resorting to bitwise operations, but if your value really is signed and you want `number%2` to yield -2 when `number` is -3, `number&1` is the way to go. Keep in mind bitshifts are not well-defined for negative numbers though. – R.. GitHub STOP HELPING ICE Nov 07 '10 at 12:17
  • Right you are! Good point... I have a bad habit of thinking unsigned when dealing with bit twidling. – Mac Nov 07 '10 at 12:23
2

Use an AND with increasing powers of two...

Marco
  • 1,346
  • 8
  • 9
2

In C, at least, you can do something like:

while (val != 0)
{
   printf("%d", val&0x1);
   val = val>>1;
}
Nathan S.
  • 5,244
  • 3
  • 45
  • 55
2

To expand on @Marco's answer with an example:

uint value = 0x82fa9281;

for (int i = 0; i < 32; i++)
{
    bool set = (value & 0x1) != 0;
    value >>= 1;

    Console.WriteLine("Bit set: {0}", set);
}

What this does is test the last bit, and then shift everything one bit.

Pieter van Ginkel
  • 29,160
  • 8
  • 71
  • 111
1

If you're already starting with a string, you could just iterate through each of the characters in the string:

var values = "1011011".Reverse().ToCharArray();
for(var index = 0; index < values.Length; index++) {
 var isSet = (Boolean)Int32.Parse(values[index]); // Boolean.Parse only works on "true"/"false", not 0/1
 // do whatever
}
Daniel Schaffer
  • 56,753
  • 31
  • 116
  • 165
1
        byte input = Convert.ToByte("1011011", 2);
        BitArray arr = new BitArray(new[] { input });
        foreach (bool value in arr)
        {
            // ...
        }
QrystaL
  • 4,886
  • 2
  • 24
  • 28
1

You can simply loop through every bit. The following C like pseudocode allows you to set the bit number you want to check. (You might also want to google endianness)

for()
{
  bitnumber = <your bit>
  printf("%d",(val & 1<<bitnumber)?1:0);
}

The code basically writes 1 if the bit it set or 0 if not. We shift the value 1 (which in binary is 1 ;) ) the number of bits set in bitnumber and then we AND it with the value in val to see if it matches up. Simple as that!

So if bitnumber is 3 we simply do this

00000100 ( The value 1 is shifted 3 left for example)

AND

10110110 (We check it with whatever you're value is)

=

00000100 = True! - Both values have bit 3 set!

Waxhead
  • 500
  • 3
  • 16