DAY 14
0

## 歡迎進入 ip 的世界，Ruby 30 天刷題修行篇第十五話

（題目來源：Codewars

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 32 bit number: 2149583361.

Write a function ip_to_int32(ip) ( JS: ipToInt32(ip) ) that takes an IPv4 address and returns a 32 bit number.

「IPv4 位址可被寫作任何表示一個 ** 32 位元整數值** 的形式，但為了方便人類閱讀和分析，它通常被寫作點分十進位的形式，即四個位元組被分開用十進位寫出，中間用點分隔。」

``````def ip_to_int32(ip)
ip_binary = ip.split(".").map { |n| n.to_i.to_s(2).rjust(8, '0') }
bits_arr = ip_binary.join("").split("")
arr = []
31.downto(0) {|n| arr.push(bits_arr[31 - n].to_i * (2 ** n))}
arr.sum
end
``````

``````require 'ipaddr'

def ip_to_int32(ip)
end
``````

``````def ip_to_int32(ip)
ip.split( '.' ).reduce( 0 ) { |total, p| total * 256 + p.to_i }
end
``````