I have a int
a=255=>1111 1111
after negating i.e ~a=10000 0000=>-64
isnt it suposed to be 0000 0000=>0
basically want to ~255 to 0
like in 8 bit binary format i.e
1111 1111 to 0000 0000
with out making it negative.
Asked
Active
Viewed 69 times
0

Dhroiden
- 53
- 9
-
2please show us your code. how are you negating? – Philipp Sander Feb 25 '14 at 12:51
-
also: an integer has 4 bytes – Philipp Sander Feb 25 '14 at 12:53
-
1answer is here http://stackoverflow.com/questions/15575520/bitwise-negation-gives-unexpected-result – Fedor Skrynnikov Feb 25 '14 at 12:53
-
You use `-` to negate (swap positive number for the same negative), and `~` to invert (flip all the bits). They are very similar, but not the same. – Peter Lawrey Feb 25 '14 at 13:01
1 Answers
5
The problem is that a
is probably of type int, which in Java takes up 4 bytes. So what you're getting is:
1111 1111 1111 1111 1111 1111 0000 0000
You should just mask the result, if you know that you're always going to work with 8 bits:
int b = ~a ^ 0xFF;

PaF
- 3,297
- 1
- 14
- 15