How to invest Bytes of an integer in java?

0

I have to go through a range of IPs, the problem is that the format that the function returns is inverted. The format that the function returns is:

First IP

108736
00000000 00000001 10101000 11000000
       0        1      168      192

Last IP

-16668480
11111111 00000001 10101000 11000000
     255        1      168      192

What I want is for them to remain:

192.168.1.0      3232235776
192.168.1.255    3232236031

This to be able to cross them in a cycle.

Edit

The for is this:

for (int i = getNetworkIp(c) + 1, bc = getBroadCastIp(c); i < bc; i++) { 
    if (isReachable(intToIp(i))) { 
        ips += "ip " + intToIp(i) + " encontrada\n";
    }
}

The problem is that when doing the cycle I have left from: 108736 to -16668480

    
asked by UselesssCat 22.03.2017 в 14:32
source

2 answers

1

You can use Integer.reverseBytes :

int numBytesReversed = Integer.reverseBytes(num);

There is also Integer.reverseque reversing all bits of a int

int numBitsReversed = Integer.reverse(num);
java.lang.Integer vínculos de API

public static int reverseBytes(int i)

Returns the value obtained by reversing the order of the bytes in representation of the two's complement of the specified int value.

public static int reverse(int i)

Returns the value obtained by inverting the order of the bits in the binary representation of two's complement of the specified int value.

    
answered by 22.03.2017 / 16:29
source
1

What you want to do is convert the " endianess ".

/* convierte de big-endian a little-endian y viceversa */
public static int convertEndianess(int i) {
    return (i & 0xff) << 24 | (i & 0xff00) << 8 | (i & 0xff0000) >> 8 | (i >> 24) & 0xff;
}

/* interpreta un int como unsigned, y lo devuelve como long */
public static long intToUnsignedAsLong(int x) {
    return ((long) x) & 0xFFFFFFFFL;
}

public static void main(String[] args) {
    int ip = 108736;
    int ip2 = convertEndianess(ip);
    System.out.println(intToUnsignedAsLong(ip2));
}

This prints 3232235776 Note that normally the conversion to long (to see it as unsigned ) is not at all necessary or desirable - if we omit that, the resulting number is -1062731520

    
answered by 22.03.2017 в 15:03