Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Last active June 19, 2018 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkfm-yamaguchi/deed8dc9c8d88885e53ca6b1e79c906f to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/deed8dc9c8d88885e53ca6b1e79c906f to your computer and use it in GitHub Desktop.
ping に10進数を指定したときの挙動についての確認スクリプト
# == ping プログラムの(?)仕様についての確認スクリプト
#
# $ ping 2915182161
#
# を実行すると,
#
# $ ping 173.194.38.81
#
# を実行したのと同じように扱われる. これは ping が引数をドット(`.`)を桁区切りとする 256 進数と同値であるため.
# 以下は, 2915182161 (10進数) が 173.194.38.81 (256進数) と同値であることを示すスクリプト.
#
# 正確には引数で与えられた IP を解釈する inet_addr の仕様によるもの.
BASE = 256
def ip2dec(ip)
ip.split(".")
.reverse.map.with_index{|d, o| [d.to_i, o] } # 位の値と桁数のペア(一番小さいのは0桁目とする)
.reduce(0){|sum, (d, o)| sum + d * BASE ** o } # BASE 進数から10進数への変換
end
def dec2ip(dec)
3.downto(0)
.map{|i| (dec >> 8 * i).modulo(BASE) }
.join(".")
end
decimal = 2915182161
ip = "173.194.38.81"
p ip2dec(ip) == decimal # => true
p dec2ip(ip2dec(ip)) == ip # => true
@tkfm-yamaguchi
Copy link
Author

dec2ip をもう少しスマートにかけないだろうか.

@tkfm-yamaguchi
Copy link
Author

tkfm-yamaguchi commented Jun 19, 2018

dec2ip の改良: 2進数化 -> 8bit ずつ 10 進数化 -> . で結合

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment