iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 13
1

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

  2149583361 ==> "128.32.10.1"
  32         ==> "0.0.0.32"
  0          ==> "0.0.0.0"

Ruby

Init

  def int32_to_ip(int32)
    # your solution
  end

Sample Testing

  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

  function int32ToIp(int32){
    //...
  }

Sample Testing

  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

  # 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

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

上一篇
見習村12 - Greed is Dice
下一篇
見習村14 - Simple Pig Latin
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言