嗨,我是 A Fei,来看看今天的题目:
(题目来源: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 address 每段转换成二进位(要补 0),并且转换成 32 bit number。嗯,前半段转换成二进位还可以理解,但後面转换成 32 bit number 真的没概念,只能呼叫 Google 大神现身说法,首先我们到 wiki 找 IPv4,其中在 「位址格式」 一节中写道:
「IPv4 位址可被写作任何表示一个 ** 32 位元整数值** 的形式,但为了方便人类阅读和分析,它通常被写作点分十进位的形式,即四个位元组被分开用十进位写出,中间用点分隔。」
嗯...好像有点头绪了,但是要怎麽把范例中的 10000000.00100000.00001010.00000001 转成 2149583361。可能 32 位元太大了,我们试着以 2 位元思考,在电脑的世界中,1 个位元会有 0 和 1 两种状态,所以 2 位元最小值是 00,最大的值是 11,可以储存的整数范围就是 0 到 3,这里可以稍微看出计算的规律,即 1 x 2^1 + 1 x 2^0 = 3,换句话说,32 位元整数换算的公式就是 32th digit number X 2^31 + 31th digit number X 2^30 ...,这样就可以算出答案了~
以下是我的解答:
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)
x = IPAddr.new(ip).to_i
end
在 Codewars 上原来可以使用 lib,我还是第一次看到!IPAddr 看名字就知道是和 ip 有关的类别,赶快去查一下手册,其中 to_i 方法写道:「Returns the integer representation of the ipaddr」。嗯,算是又学到了一招呢。
不使用 lib 的解法:
def ip_to_int32(ip)
ip.split( '.' ).reduce( 0 ) { |total, p| total * 256 + p.to_i }
end
以上就是今天的解题纪录,大家掰掰
>>: Day17 - this&Object Prototypes Ch3 Objects - Iteration 开头
Coroutine 中如果要执行非同步程序,则需要把耗时任务写在 suspend 函式中,并且在一个...
最近在思考工具机在使用C#的图形化介面 因此来查一下看长的怎样 https://docs.micro...
09-08-2021 本章内容 THE STATE HOOK Hook 可以做的事情 规则 使用us...
变量或称变数,是是用於存储信息的容器。 x='winnie'; y=5; 在数学代数中,使用字母(如...
再刚开始阅读文章时,必须先了解一下各部位的名称,本篇就来快速介绍手机的各部位一下吧。 1.Statu...