int32 to IPv4 in Java

The challenge

Take the following IPv4 address: 128.32.10.1

This address has 4 octets where each octet is a single byte (or 8 bits).

  • 1st octet 128 has the binary representation: 10000000
  • 2nd octet 32 has the binary representation: 00100000
  • 3rd octet 10 has the binary representation: 00001010
  • 4th octet 1 has the binary representation: 00000001

So 128.32.10.1 == 10000000.00100000.00001010.00000001

Because the above IP address has 32 bits, we can represent it as the unsigned 32-bit number: 2149583361

Complete the function that takes an unsigned 32-bit number and returns a string representation of its IPv4 address.

Examples

2149583361 ==> "128.32.10.1"
32         ==> "0.0.0.32"
0          ==> "0.0.0.0"

The solution in Java code

Option 1:

public class Solution {
  public static String longToIP(long ip) {
    return String.format("%d.%d.%d.%d", ip>>>24, (ip>>16)&0xff, (ip>>8)&0xff, ip&0xff);
  }
}

Option 2:

public class Solution {
    public static String longToIP(final long ip) {
        return ((ip >> 24) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                (ip & 0xFF);
    }
}

Option 3:

public class Solution {
  public static String longToIP(long ip) {
    StringBuilder sb = new StringBuilder();
    long mask = (1<<8)-1;
    
    sb.append(ip>>>24 & mask);
    sb.append('.');
    sb.append(ip>>>16 & mask);
    sb.append('.');
    sb.append(ip>>>8 & mask);
    sb.append('.');
    sb.append(ip & mask);
    
    return sb.toString();
  }
}

Test cases to validate our solution

import org.junit.Test;

import java.util.Random;

import static org.junit.Assert.assertEquals;

public class SolutionTest {
  @Test
  public void sampleTest() {
    assertEquals("128.114.17.104", Solution.longToIP(2154959208L));
    assertEquals("0.0.0.0", Solution.longToIP(0));
    assertEquals("128.32.10.1", Solution.longToIP(2149583361L));
  }

  private static Random random = new Random();

  private static String solution(long ip) {
    return (ip >>> 24) % 256 + "." + (ip >>> 16) % 256 + "." + (ip >>> 8) % 256 + "." + ip % 256;
  }

  @Test
  public void randomTest() {
    final int Tests = 100;
    for (int i = 0; i < Tests; ++i) {
      long thirtyBits = random.nextInt(1 << 30);
      long twoBits = random.nextInt(1 << 2);
      long fullRange = (thirtyBits << 2) | twoBits;

      String expected = solution(fullRange);
      String actual = Solution.longToIP(fullRange);

      assertEquals(expected, actual);
    }
  }
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments