1. Member
Join Date
Jun 2010
Posts
2
Rep Power
0

## System.out.println(040|343);

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 ?

2. Originally Posted by satheshshiva
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

3. Senior Member
Join Date
Apr 2010
Location
Posts
278
Rep Power
12
I checked that
System.out.println(040|343); prints "345"
With small program I get "375"
Java Code:
public class Bitwise {
public static void main(String[] args) {
System.out.println(040 | 343);
}
}
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 ).

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).

4. Member
Join Date
Jun 2010
Posts
2
Rep Power
0
Thanks to both of you above.

Sorry for the typo.. its "375"

5. 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 from
Java Code:
System.out.println(040|343)
at an interview lol.
Last edited by Lil_Aziz1; 06-26-2010 at 08:00 PM.

6. Senior Member
Join Date
Apr 2010
Location
Posts
278
Rep Power
12
When one a person ever use bitwise comparison in practical applications?
It's very good to use bitwise operators in many occasions.

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).

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•