見習村13 - int32 to IPv4

13 - int32 to IPv4

Don’t say so much, just coding…

Instruction

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

1
2
3
2149583361 ==> "128.32.10.1"
32 ==> "0.0.0.32"
0 ==> "0.0.0.0"

Ruby

Init

1
2
3
def int32_to_ip(int32)
# your solution
end

Sample Testing

1
2
3
Test.assert_equals(int32_to_ip(2154959208), "128.114.17.104") 
Test.assert_equals(int32_to_ip(0), "0.0.0.0")
Test.assert_equals(int32_to_ip(2149583361), "128.32.10.1")

Javascript

Init

1
2
3
function int32ToIp(int32){
//...
}

Sample Testing

1
2
3
Test.assertEquals( int32ToIp(2154959208), "128.114.17.104", "wrong ip for interger: 2154959208") 
Test.assertEquals( int32ToIp(0), "0.0.0.0", "wrong ip for integer: 0")
Test.assertEquals( int32ToIp(2149583361), "128.32.10.1", "wrong ip for integer: 2149583361")

Thinking

想法(1): 先需要去了解 IPv4 是什麼
想法(2): 轉為 binary 後還要 8 個為一群,並且補 0

https://ithelp.ithome.com.tw/upload/images/20200928/20120826hZNjejxq8g.jpg
圖片來源:Unsplash Damian Zaleski

Hint & Reference

Solution

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Solution 1
def int32_to_ip(int32)
int32.to_s(2)
.rjust(32, '0')
.scan(/.{8}/)
.map{ |s| s.to_i(2) }
.join('.')
end

# Solution 2
require 'ipaddr'

def int32_to_ip(int32)
IPAddr.new(int32, Socket::AF_INET).to_s
end

Javascript

1
2
3
4
5
6
7
8
// Solution 1
function int32ToIp(int32){
return int32.toString(2)
.padStart(32, '0')
.match(/([01]{8})/g)
.map(x => parseInt(x, 2))
.join('.')
}