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?
-
3What's an "int inside another int"?user1040049– user10400492011-11-22 04:26:38 +00:00Commented 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 variablemouviciel– mouviciel2011-11-23 16:37:09 +00:00Commented Nov 23, 2011 at 16:37
Add a comment
|
2 Answers
NSString * binary = @"0011010";
long value = strtol([b UTF8String], NULL, 2);
1 Comment
Seany242
wow I don't know how this works but it makes life so much easier. How does this work?
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
Seany242
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.