Which of the following give back 63 as long (in Java) and how?
0x0 0x1 0x2 0x4 0x8 0x10 0x20 I'm working with NetworkManager API flags if that helps. I'm getting 63 from one of the operations but don't know how should I match the return value to the description.
Thanks
3 Answers
63 is 32 | 16 | 8 | 4 | 2 | 1, where | is the binary or operator.
Or in other words (in hex): 63 (which is 0x3F) is 0x20 | 0x10 | 0x8 | 0x4 | 0x2 | 0x1. If you look at them all in binary, it is obvious:
0x20 : 00100000 0x10 : 00010000 0x08 : 00001000 0x04 : 00000100 0x02 : 00000010 0x01 : 00000001 And 63 is:
0x3F : 00111111 If you're getting some return status and want to know what it means, you'll have to use binary and. For example:
if (status & 0x02) { } Will execute if the flag 0x02 (that is, the 2nd bit from the right) is turned on in the returned status. Most often, these flags have names (descriptions), so the code above will read something like:
if (status & CONNECT_ERROR_FLAG) { } Again, the status can be a combination of stuff:
// Check if both flags are set in the status if (status & (CONNECT_ERROR_FLAG | WRONG_IP_FLAG)) { } P.S.: To learn why this works, this is a nice article about binary flags and their combinations.
7I'd give you the same answer as Chris: your return value 0x63 seems like a combination of all the flags you mention in your list (except 0x0).
When dealing with flags, one easy way to figure out by hand which flags are set is by converting all numbers to their binary representation. This is especially easy if you already have the numbers in hexadecimal, since every digit corresponds to four bits. First, your list of numbers:
0x01 0x02 0x04 ... 0x20 | | | | | | | | V V V V 0000 0001 0000 0010 0000 0100 ... 0010 0000 Now, if you take your value 63, which is 0x3F (= 3 * 161 + F * 160, where F = 15) in hexadecimal, it becomes:
0x3F | | V 0011 1111 You quickly see that the lower 6 bits are all set, which is an "additive" combination (bitwise OR) of the above binary numbers.
63 (decimal) equals 0x3F (hex). So 63 is a combination of all of the following flags:
0x20 0x10 0x08 0x04 0x02 0x01 Is that what you were looking for?