For bitwise operations in Java, do I need to take care that most of the numeric types in Java are signed?

This is really a basic question, but I never convinced myself that my intuitive answer β€œdoesn't matter” is correct, so maybe someone has a good way to figure this out:

If all I want to do with one of the primitive numeric types in Java is bitwise arithmetic, can I just process it as if it were an unsigned value, or I need to avoid negative numbers, i.e. always keep the highest order bit set to 0? For example, is it possible to use int as if it were a 32-bit unsigned number, or should I use only the least significant 31 bits?

I am looking for the most general answer possible, but let me give you an example: let them say that I want to store 32 flags. Can I store all of them in one int if I use something like

store = store & ~(1 << index) | (value << index) 

set the index flag to value and something like

 return (store & (1 << index)) != 0 

to get the index flag? Or can I run into any problems with this or similar code if I ever set the flag from index 31 to 1?

I know that I always need to use β†’> instead of β†’ for the right offset, but is this the only problem? Or can there be other things wrong related to two additional representations of negative numbers when I use the most significant bit?

+4
source share
2 answers

There are legitimate reasons to use >> also in this context (the general case is to create a mask that should be 0 or -1 directly, without having to reset the mask that is 0 or 1), so there really is no concern. Just be careful what you do to make sure it matches your intentions.

Operations that take care of subscription (i.e. have different signed and unsigned forms with different semantics):

  • right shift
  • division (unsigned form not available in Java)
  • modulo (unsigned form not available in Java)
  • comparisons (except equality) (unsigned forms are not available in Java)

Operations that do not care about subscription are as follows:

  • and
  • or
  • exclusive
  • Adding
  • Subtraction
  • denial of two additions ( -x means ~x + 1 )
  • one addition ( ~x means -x - 1 )
  • left shift
  • Multiplication
+2
source

I know that I always need to use β†’> instead of β†’ for the right offset, but is this the only problem?

Yes, this is the only problem. The left shift works the same on signed and unsigned numbers; the same thing happens for AND ing, OR ing, and XOR ing. As long as you use >>> to shift to the right, you can use all 32 bits of the signed int .

+3
source

Source: https://habr.com/ru/post/1439051/


All Articles