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?

2
  • 3
    What's an "int inside another int"? Commented Nov 22, 2011 at 4: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 Commented Nov 23, 2011 at 16:37

2 Answers 2

5
NSString * binary = @"0011010";
long value = strtol([b UTF8String], NULL, 2);
Sign up to request clarification or add additional context in comments.

1 Comment

wow I don't know how this works but it makes life so much easier. How does this work?
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];

2 Comments

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?
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. It's similar to an if statement. a % b is the modulo operator. It returns the remainder of the division a/b.

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.