-2

for example I have such number 4302033, it is in binary system 10000011010010011010001, and I need to make inversion, but when I do inversion, it turns out so 11111111101111100101101100101110, and how to take away these units in the beginning

azro
  • 53,056
  • 7
  • 34
  • 70
  • 1
    what you call inverse of a number? bitwise inverse, additive inverse, multiplicative inverse (probably not), ...? – user16320675 Apr 10 '22 at 09:28

1 Answers1

1

You are wrong!

The binary representation of 4302033 is not 10000011010010011010001!

In fact it is 000000000010000011010010011010001.

In Java, an int has 32 bits (check Integer.SIZE), always, no matter how large the number is that you store within that int field. Even for zero, it has those 32 bit (Ok, the first (most left) bit is not really used for the value, but for the sign).

This means that when you invert an int, you invert all these 32 bits, even including those left from the first 1 (those you referred to as "these units at the beginning").

If this is unwanted, you have to take precautions against that:

var value = 4302033;
var leadingZeros = Integer.numberOfLeadingZeros( value );
var inverted = value ^ 0xFFFFFFFF << leadingZeros >>> leadingZeros;
System.out.println( Integer.toBinaryString( value );
System.out.println( Integer.toBinaryString( inverted );

tquadrat
  • 3,033
  • 1
  • 16
  • 29