0

I will ask a rather simple question that was's a surprise to me. I wanted to port a simple C code to java and in this code it used an int as boolean. Inside the code it inverted it several times like:

c = !c;

So naturally at first I thought a boolean will work fine. The invertion did not work though (using the Binary Ones Complement Operator ~).

I have tried byte also (after all I just needed a boolean) but the peculiar thing is that this code does not compile indicating an error Type mismatch:

byte c = 0;
c = ~c; //<= here is the error

The eclipse suggested solution was c = (byte) ~c; (conversion to byte).

So my question is whether there is a Binary Ones Complement Operator that operates on booleans and bytes? Should it be overloaded for different types? I just want to invert the value of a boolean that shouldn't be too hard.

P.S.1 long works smoothly with ~ though. P.S.2 I know how to work with int and then convert it to boolean but I thought a faster implementation should exist.

Eypros
  • 5,370
  • 6
  • 42
  • 75
  • Java has the `!` logical not operator too. Just use that. – Ben Jun 23 '14 at 11:53
  • c is a different thing all together, if u r using c, you are using c, otherwise use what java defines – maress Jun 23 '14 at 11:55
  • While this discussion is about xor, it applies to bitwise operators in general: http://stackoverflow.com/questions/2003003/why-does-the-xor-operator-on-two-bytes-produce-an-int – Brett Okken Jun 23 '14 at 11:55
  • The reason `long` works without an additional cast is that `~` applied to a `long` produces a `long`, while `~` applied to a `byte` produces an `int`. – Sergey Kalinichenko Jun 23 '14 at 12:01
  • @Brett Okken, that was also a useful link. – Eypros Jun 23 '14 at 12:07
  • There is no such thing as the "binary one's complement operator". `~` is the _bitwise complement_ operator. Whether the result can be interpreted as one's complement, or two's complement, or something else, has nothing to do with that operator. Anyway, it is not what you need for this task. – Lundin Jun 23 '14 at 12:48
  • Also, Eclipse is an IDE. It will not make suggestions about how to change the contents your code. – Lundin Jun 23 '14 at 12:50

1 Answers1

1

Use boolean in Java and negate it with !.

adjan
  • 13,371
  • 2
  • 31
  • 48