I was asked this in a Java Interview. I checked that
System.out.println(040|343); prints "345". But How? Whats the operation taking place ?
Printable View
I was asked this in a Java Interview. I checked that
System.out.println(040|343); prints "345". But How? Whats the operation taking place ?
Any integer starting with a zero (0) introduces an octal representation of the number so 040 == 32 in decimal. The vertical bar (|) is the bitwise or operator, so 032 | 343 in binary is: 100000 | 101011001 == 101111001 which is 375 in decimal. I don't know where they got 345 as an answer from ...
kind regards,
Jos
With small program I get "375"Quote:
I checked that
System.out.println(040|343); prints "345"
when you have octal number you can convert it to binary number by number. Every octal number consist of 3 binary numbers ( 2 ^ 3 = 8 ).Code:public class Bitwise {
public static void main(String[] args) {
System.out.println(040 | 343);
}
}
So how convert 40 to binary?
4 = 100 ( 1 * 2 ^ 2 + 0 * 2 ^ 1 + 0 * 2 ^ 0 )
0 = 000 ( 0 * 2 ^ 2 + 0 * 2 ^1 + 0 * 2 ^ 0)
Then you have 40 in binary 100000.
in decimal:
100000 = (1 * 2 ^ 5 + 0 * 2 ^ 4 + 0 * 2 ^ 3 + 0 * 2 ^ 2 + 0 * 2 ^ 1 + 0 * 2 ^ 0 ) = 32
and finally you have (32 | 343).
Thanks to both of you above.
Sorry for the typo.. its "375"
When one a person ever use bitwise comparison in practical applications?
EDIT: I'd be a bit chagrined if my imminent boss asked me for the result fromat an interview lol.Code:System.out.println(040|343)
It's very good to use bitwise operators in many occasions.Quote:
When one a person ever use bitwise comparison in practical applications?
For example if you have device with 100.000 characteristic, it's cheaper to work with bits.
100.000 characterictics (on/off) implemented with bits is like working with 100.000 / 8 = 12.500.
Program is faster, but is difficult to implement.
Bitwise operators is a connection with low level languages (asembly languague).