1

How do I get the value of a certain bit from a byte or integer? The only similar answer that I've been able to find is for a specific character inside a string. I am trying to convert a binary number to a decimal number, and perhaps there is a much simpler way to do this, but I was thinking of this: multiplying 2^(position of integer from right) by either a 1 or 0, depending on the value of the integer at the position previously mentioned. Any tips?

Seany242
  • 373
  • 7
  • 20
  • 3
    What's an "int inside another int"? –  Nov 22 '11 at 04:26
  • Though not an exact duplicate, you may find this question helpful: [C/C++ check if one bit is set in, i.e. int variable](http://stackoverflow.com/q/523724/45249) – mouviciel Nov 23 '11 at 16:37

2 Answers2

5
NSString * binary = @"0011010";
long value = strtol([b UTF8String], NULL, 2);
Adithya Surampudi
  • 4,354
  • 1
  • 17
  • 17
1

There are multiways of obtaining the value of bit within a byte or integer. It all depends on your needs.

One way would be to use a mask with bitwise operators.

int result = sourceValue & 8;    // 8 ->  0x00001000
// result non zero if the 4th bit from the right is ON.

You can also shift bits one by one and read, say, the right-most bit.

for (int i = 0;  i < 8; i++)
    NSLog(@"Bit %d is %@", i, (sourceValue % 2 == 0) ? @"OFF" : @"ON");
    sourceValue = sourceValue >> 1;  // shift bits to the right for next loop.
}

Or if you just want the text representation for an integer, you could let NSNumber do the work:

NSString* myString = [[NSNumber numberWithInt:sourceValue] stringValue];
  • thanks a ton! I'm pretty new to programming, could you explain this a bit? Is source value an int? and what does the (sourceValue % 2 == 0) ? @"OFF" : @"ON" part do? – Seany242 Nov 23 '11 at 19:18
  • In my code samples, `sourceValue` is an `int` and holds the value you want to extract bits from. The `(condition) ? value1 : value2` part is a [ternary operator](http://stackoverflow.com/questions/2595392/what-does-the-question-mark-and-the-colon-ternary-operator-mean-in-objectiv). It's similar to an if statement. `a % b` is the [modulo operator](http://en.wikipedia.org/wiki/Modulo_operation). It returns the remainder of the division `a/b`. –  Nov 23 '11 at 19:33