programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Bitwise inversion of 0

Ranch Hand
Posts: 324
I want to invert the integer value 0 in such a way that all its bits are set to 1. Please help me how to do it?

Thanks

Ranch Hand
Posts: 237
Amirr Rafique wrote:I want to invert the integer value 0 in such a way that all its bits are set to 1. Please help me how to do it?

You use the bitwise not operator ~. To invert all 0's in 0 you do ~0.

If you print ~0 you'll get -1. That's because all 1's is the internal coding for -1. This means -1 is an alternate way of having an int with only 1's.

Amirr Rafique
Ranch Hand
Posts: 324
Thanks for your reply Embla. I have one confusion in digesting this concept, As per your post what i understood is

1111 1111 1111 1111 1111 1111 1111 1111 => -1

then what will be value of following bit pattern

1000 0000 0000 0000 0000 0000 0000 0001

Thanks

Marshal
Posts: 56610
172
You need to know how to convert binary to decimal numbers. Try it with 1000_0001 in 8 bits two's complement arithmetic first. Remember a 1 in the rightmost bit means 1, then 2, then 4, etc, but in an 8-bit two's complement number, imagine the leftmost bit means -128. This is not how complement arithmetic is defined, but it will give the same result.
Use a calculator and find out what 2^7, 2^15, 2^31 and 2^63 mean, or look for the Integer, Long, Byte and Short classes, and find their field called MIN_VALUE then the link to "constant field values" in the API documentation.

Embla Tingeling
Ranch Hand
Posts: 237
Amirr Rafique wrote:Thanks for your reply Embla. I have one confusion in digesting this concept, As per your post what i understood is

1111 1111 1111 1111 1111 1111 1111 1111 => -1

then what will be value of following bit pattern

1000 0000 0000 0000 0000 0000 0000 0001

As has been mentioned integers (long, int, short and byte) in Java are stored internally in a so called two's complement format. Positive numbers are as expect but the negative are kind of the other way around, like

000 : 0
001 : 1
010 : 2
011 : 3
100 : -4
101 : -3
110 : -2
111 : -1

Analogously if you have,

1000 0000 0000 0000 0000 0000 0000 0000

that will be the most negative 32 bit number there is. If you instead have a 1 at the end like

1000 0000 0000 0000 0000 0000 0000 0001

it will be 1 less small. So that's the second most negative 32-bit int there is.

 It is sorta covered in the JavaRanch Style Guide.