Search code examples
javaipv6

Bitwise operations on 128 bit in java


I have binary representation of two IPv6 addresses

For example: First String is binary representation of

'2001:4E8:0:4000:0:0:0:0'
'00100000000000010000010011101000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000'

Second string binary representation

 '0:0:0:0:ffff:ffff:ffff:ffff'
 '00000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111'

Now I want to do a biwise 'AND' operation on the IPv6 Address and its mask. What would be a good way to achieve this in java?

P:S: Integer.parseInt supports only 32 bit operations


Solution

  • You can use BigInteger's and() :

    BigInteger first = new BigInteger("00100000000000010000010011101000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000",2);
    BigInteger second = new BigInteger("00000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111",2);
    BigInteger and = first.and(second);