Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise Operations Java - Long to Binary

I found this code for an arithmetic encoder and I'm a bit confused as to where the values mentioned in the comments are coming from.

Can anyone go through whats happening in these operations step by step?

protected final long STATE_SIZE  = 32;  // Number of bits for 'low' and 'high'. Must be in the range [1, 62] (and possibly more restricted).
    protected final long MASK        = (1L << (STATE_SIZE - 0)) - 1;  //  111...111, all ones

These are my assumptions so far:

  • "MASK" is defining a Long which is set to 1
  • Then shifting this by 32 (I thought) would give 100000...00 (which I have verified myself in java.
  • Then I get stuck. I'm not sure how the "-1" makes them all change to 1's?

I've tried it out myself using this code:

long STATE_SIZE  = 32;
        long shifted = 1L << STATE_SIZE-0;
        long shiftedMinusOne = shifted -1;
        System.out.println("Shifted: " + shifted);
        System.out.println("Shifted Minus One: " + shiftedMinusOne);
        System.out.println("Shifted Binary: " + Long.toBinaryString(shifted));
        System.out.println("Shifted Minus One Binary: " + Long.toBinaryString(shiftedMinusOne));

And my output is:

Shifted: 4294967296
Shifted Minus One: 4294967295
Shifted Binary: 100000000000000000000000000000000
Shifted Minus One Binary: 11111111111111111111111111111111

Could anyone tell me if I'm doing something wrong or why the -1 makes them all 1's?

like image 854
Aimee Jones Avatar asked Apr 10 '26 02:04

Aimee Jones


1 Answers

Please note the difference in length:

  100000000000000000000000000000000 - 1
=  11111111111111111111111111111111

This is a correct binary subtraction. You are doing okay :)

like image 140
sulai Avatar answered Apr 11 '26 15:04

sulai