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

- 06-26-2010, 11:17 AMsatheshshivaSystem.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 ? - 06-26-2010, 11:48 AMJosAH
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 - 06-26-2010, 12:20 PMcselicQuote:

I checked that

System.out.println(040|343); prints "345"

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). - 06-26-2010, 02:30 PMsatheshshiva
Thanks to both of you above.

Sorry for the typo.. its "375" - 06-26-2010, 07:49 PMLil_Aziz1
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 fromCode:`System.out.println(040|343)`

- 06-26-2010, 11:26 PMcselicQuote:

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