Search code examples
javafilterbytebitparseint

in java i am trying to use & with a filter to get each byte of an integer it works for the last 3 bytes but the first throws a number format exception


hi thanks in advance for your help, i am trying to write a program that will allow you to reorder the bytes in a integer i plan on separating the bytes with a filter like so

int number = 3;
    int filter = Integer.parseInt("11111111000000000000000000000000",2);
    return number & filter;

i wrote a switch statement to select between the four different filters

  1. first byte filter = "11111111000000000000000000000000"
  2. second byte filter = "00000000111111110000000000000000"
  3. third byte filter = "00000000000000001111111100000000"
  4. forth byte filter = "00000000000000000000000011111111"

the second to forth filters work but the first one throws a number format exception is this something to do with the sign of the integer?

after seperating the bytes like this i want to use left and right shift to move the bytes and use the OR bitwise operator to combine them back in to a 32 bit integer but in a different order thanks again for any help.


Solution

  • The method Integer.parseInt does not expect you to directly pass the bytes you want to set into it, instead it simply interprets the passed String as a binary number so that

    11111111000000000000000000000000

    in binary is

    4278190080

    in decimal system. Which itself is bigger than the maximum value an Integer can hold.

    If you want to define your int variables with a binary pattern, then you can quite easily do that which standard java syntax:

    // using hex syntax
    int firstByteFilter = 0xFF000000;
    int secondByteFilter = 0x00FF0000;
    

    and so on. There is no need to involve the parseInt method.