Don't say so much, just coding...
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
10000000
00100000
00001010
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"
def int32_to_ip(int32)
# your solution
end
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")
function int32ToIp(int32){
//...
}
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")
想法(1): 先需要去了解 IPv4 是什麼
想法(2): 轉為 binary
後還要 8
個為一群,並且補 0
# 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
// Solution 1
function int32ToIp(int32){
return int32.toString(2)
.padStart(32, '0')
.match(/([01]{8})/g)
.map(x => parseInt(x, 2))
.join('.')
}