Skip to main content

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange
Asked
Modified 2 days ago
Viewed 3k times
21
\$\begingroup\$

Write the shortest function to convert an IP address into its integer representation and output it as an integer.

To change an IPv4 address to its integer representation, the following calculation is required:

  • Break the IP address into its four octets.
  • (Octet1 * 16777216) + (Octet2 * 65536) + (Octet3 * 256) + (Octet4)

Sample Input

192.168.1.1           10.10.104.36           8.8.8.8

Sample Output

3232235777            168454180              134744072
\$\endgroup\$
2
  • 2
    \$\begingroup\$ I think this would be better if there was a restriction in place prohibiting a language's built-in functions. \$\endgroup\$
    Nathan Osman
    –  Nathan Osman
    2011-02-06 20:04:20 +00:00
    Commented Feb 6, 2011 at 20:04
  • \$\begingroup\$ @George - Yea, it would have been, but people had already done it before the I could put that in - I honestly didn't think about it. \$\endgroup\$
    Kyle Rosendo
    –  Kyle Rosendo
    2011-02-07 05:51:43 +00:00
    Commented Feb 7, 2011 at 5:51

60 Answers 60

1
2
1
\$\begingroup\$

Perl 6, 16 bytes

{:256[m:g/\d+/]}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

C (gcc) -m32 / POSIX, 33 bytes

f(a){inet_aton(a,&a);a=ntohl(a);}

Try it online!

On a big-endian platform, you could simply define a macro with -Df=inet_aton for 13 bytes.

\$\endgroup\$
1
\$\begingroup\$

APL(NARS), 16 chars, 32 bytes

{256⊥⍎¨⍵⊂⍨⍵≠'.'}

test

  f←{256⊥⍎¨⍵⊂⍨⍵≠'.'}
  f¨'192.168.1.1' '10.10.104.36' '8.8.8.8'
3232235777 168454180 134744072 
\$\endgroup\$
1
\$\begingroup\$

Jelly, 6 bytes

ṣ”.Vḅ⁹

Try it online!

How it works

ṣ”.Vḅ⁹  Main link (monad). Input: string
ṣ”.     Split at dots
   V    Convert to numbers
    ḅ⁹  Convert base 256 to integer
\$\endgroup\$
1
\$\begingroup\$

Pxem, Filename: 58 bytes + Content: 0 bytes = 58 bytes.

  • Filename (escaped): ._\377\001.+.c.c.!.!.!.i.s._\377\001.+.c.!.!.+.i.s._\377\001.+.!.+.i.s._.+.n
  • Content: empty

Problem is that my implementation of Pxem supports literal value up to 255; needed to make greatee values by myself.

Usage

Via stdin/stdout. Accepts only one input at once.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

K (ngn/k), 10 bytes

256/.'"."\

Try it online!

  • "."\ split string input on .'s
  • .' convert each string to its integer
  • 256/ convert from base-256
\$\endgroup\$
1
\$\begingroup\$

Nibbles, 3.5 bytes

`@256_

Attempt This Online!

Explanation

`@256_
     _ Read all numbers from STDIN (ignoring the periods)
`@     Convert from base
  256  256
\$\endgroup\$
1
\$\begingroup\$

Python 3 63 bytes

lambda x:sum(int(n)<<8*(3-i)for i,n in enumerate(x.split('.')))

What it looks like. Takes the sum of the numbers bitshifted 8 * (3 - the position it's in).

\$\endgroup\$
0
\$\begingroup\$

Powershell - 53

Variation on Ty Auvil's answer, which is a variation on Joey's answer:

%{([ipaddress]($_.split('.')[3..0]-join'.')).address}

PS C:\> '192.168.1.1' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
3232235777
PS C:\> '10.10.104.36' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
168454180
PS C:\> '8.8.8.8' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
134744072

I would have just made a suggestion in the comments, but not enough rep.

\$\endgroup\$
0
\$\begingroup\$

ASM - 98 byte executable (WinXP command shell), about 485 characters

Assemble using A86. Badly formed IP addresses generate undefined output.

    mov si,82h
    mov di,10
    mov bp,l3
    fldz
    push l2
    push l0
    push l0
    push l0
 l0:xor ax,ax
    xor cx,cx
 l1:add ax,cx
    mov [bp+di],ax
    mul di
    mov cx,ax
    lodsb
    sub al,'0'
    jnc l1
    fild w[bp]
    fmulp
    fild w[bp+di]
    faddp  
    ret
 l2:fbstp [si]
    mov bx,di
    mov di,bp
 l4:dec bx
    jz l5
    mov al,[si+bx-1]
    aam 16
    add ax,'00'
    xchg al,ah
    stosw
    jmp l4
 l5:mov al,'$'
    stosb
    lea di,[bp-1]
 l6:inc di
    cmp b[di],'0'
    je l6
 l7:cmp b[di],al
    jne l8
    dec di
 l8:mov dx,di
    mov ah,9
    int 21h
    ret
 l3:dw 256
\$\endgroup\$
0
\$\begingroup\$

C (91)

Not going to win anyway, so I tried to be a bit creative. Tested on 32-bit GCC 4.4.3.

main(a,c,b)char**c,*b;{c=c[1];for(b=&a+1;c=strtok(c,".");c=0)*--b=atoi(c);printf("%u",a);}
\$\endgroup\$
0
\$\begingroup\$

Scala 59 chars:

def f(i:String)=(0L/:i.split("\\.").map(_.toInt))(_*256+_)
\$\endgroup\$
0
\$\begingroup\$

Perl with builtins (35):

unpack"N",pack"C4",split/\./,shift;  

Perl without builtins (42):

split/\./,shift;$s+=$_<<@_*8while$_=shift;
\$\endgroup\$
0
\$\begingroup\$

Perl, 14 characters:

sub _{unpack'L>',pop}

# Example usage
print _(10.10.104.36) # prints 168454180
\$\endgroup\$
1
  • 7
    \$\begingroup\$ How do you make that 14 characters? I count 21. \$\endgroup\$
    Peter Taylor
    –  Peter Taylor
    2012-10-03 10:49:21 +00:00
    Commented Oct 3, 2012 at 10:49
0
\$\begingroup\$

Python (No eval) - 67

c=lambda x:long(''.join(["%02X"%long(i) for i in x.split('.')]),16)
\$\endgroup\$
1
  • 2
    \$\begingroup\$ can you not shorten it a few more characters by using int() instead of long()? \$\endgroup\$
    Wug
    –  Wug
    2012-09-24 06:58:20 +00:00
    Commented Sep 24, 2012 at 6:58
0
\$\begingroup\$

Mathematica, 53 chars

f=FromDigits;f[f/@StringSplit[InputString[],"."],256]
\$\endgroup\$
0
\$\begingroup\$

Jelly, 13 bytes

4Ḷ⁹*U
ṣ”.V×¢S

Try it online!

I don't think Jelly has a builtin for this. At least, I couldn't find one.

\$\endgroup\$
0
\$\begingroup\$

J, 21 bytes

[:256&#.[:".;._1'.'&,

Try it online!

explanation

[: 256&#. [: ".;._1 '.'&,          
[: 256&#.                   NB. assuming a base 256 list, 
                            NB. convert the following to decimal:
                    '.'&,   NB. the input with a dot appended
          [: ".;._1         NB. split at dots and converted to ints
\$\endgroup\$
0
\$\begingroup\$

Java 8, 83 bytes

i->{long u=0;for(int j=0;j<4;)u+=new Long(i.split("\\.")[j])<<(24-8*j++);return u;}

Try it online!

Could have saved 10 bytes by moving the initialisation of u and j "up" a level but I'm not entirely sure that's allowed so I went for the safe version of my solution.

\$\endgroup\$
0
\$\begingroup\$

Burlesque - 11 bytes

'.;;ri256ug

'.;;           split by `.`
    ri         read integer
      256ug    undigits base 256

Try it online.

\$\endgroup\$
0
\$\begingroup\$

Kotlin, 50 bytes

{it.split(".").fold(0L){a,v->v.toInt()+(a shl 8)}}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Japt, 10 4 bytes

nG²o

Try it

 G       :16
  ²      :Squared
   o     :Range [0,G²)
n        :Convert input string from that base to base-10 integer
\$\endgroup\$
0
\$\begingroup\$

min, 53 bytes

"." split 3 :a (int 256 a pow * a 1 - @a int) map sum

Takes IP address as string on stack. Leaves the converted number on top of stack.

\$\endgroup\$
0
\$\begingroup\$

Pinecone, 266 bytes

u:IntArray:4;s:"".input;k:IntArray:s.len;k.set:0,-1;n:1
i:0|i<s.len|i:i+1@((s.sub:i,i+1)="."?(k.set:n,i;n:n+1))k.set:n,s.len;i:1|i<n+1|i:i+1@(j:s.sub:((k.get:i-1)+1),(k.get:i)u.set:(i-1),(j.Int))print:((u.get:0)*16777216)+((u.get:1)*65536)+((u.get:2)*256)+(u.get:3)
\$\endgroup\$
0
\$\begingroup\$

Thunno 2, 5 bytes

'./ɠḋ

Try it online!

Explanation

'./ɠḋ  '# Implicit input
'./    '# Split it on "."s
   ɠḋ   # Convert from base-256
        # Implicit output
\$\endgroup\$
0
\$\begingroup\$

Vyxal 3, 6 bytes

'.s⌊⑦⊣

Vyxal It Online!

Well this was easier than I thought...

'.s⌊⑦⊣­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌­
'.s⌊    # ‎⁡Split on . and convert to integers
    ⑦⊣  # ‎⁢Base 256
💎

Created with the help of Luminespire.

\$\endgroup\$
0
\$\begingroup\$

WhatLang, 30 bytes

'.split@num#|\&&\(256*+)::++@.

Try it here!

\$\endgroup\$
0
\$\begingroup\$

Uiua, 33 27 24 bytes

⌝⊥256⇌⊜⋕≠@..

Uiua pad this online

Explanation

            .  # duplicate input string 
      ⊜⋕≠@.   # split at `.` into array of integers
     ⇌         # reverse it, then treating entries as...
⌝⊥256          # ...digits of a base-256 number

Changes

  • 33 bytes: initial version
  • 27 bytes (-6): use "anti-base" ⌝⊥ instead of calculating the base values by hand /+×ⁿ⇌⇡4
  • 24 bytes (-3): move parse into split drops need for box arrays (yeah, shorter than Bash!)
\$\endgroup\$
1
  • 1
    \$\begingroup\$ The /+×ⁿ⇌⇡4 part can be replaced with ⌝⊥ \$\endgroup\$
    YufangIGuess
    –  YufangIGuess
    2025-10-14 09:29:38 +00:00
    Commented Oct 14 at 9:29
0
\$\begingroup\$

awk

A vanilla no-frills adaptation of the Horner's Polynomial Evaluation Method to IPv4 addresses. But unlike the standard notation, I prefer placing all the base scalars on one side, so all the coefficients could be placed sequentially adjacent one another.

echo '192.168.1.1
      10.10.104.36
      8.8.8.8' |

awk -F. '$0=_*(_*(_*$1+$2)+$3)+$4' \_=256

3232235777
168454180
134744072

If you're curious, arithmetic expression (and bit-wise-ops only variant) expands out to -

256 * (256 * (256 * (192) + 168) + 1) + 1

  1 | (1 | (168 | (192) << 8) << 8) << 8

Personally I prefer the arithmetic expression because you can see the 4 components of the address exactly in the same order as its appears in dot-(.) form, but requires them to be written in little-endian order in order to conform with the preference of isolating scalars of the base versus the coefficients instead of having them chaotically interweaved.

The parens ( ) around both 192 are absolutely superfluous. I only included them for completeness and clarity of the illustration.

\$\endgroup\$
0
\$\begingroup\$

Tcl, 66 bytes

proc C h {expr [lmap c [split $h .] {list +($c<<8*(4-[incr e]))}]}

Try it online!


Tcl, 66 bytes

proc C h {expr [lmap c [split $h .] {list +$c*256**(4-[incr e])}]}

Try it online!


# [Tcl], 71 bytes
proc C {h e\ 32} {expr [lmap c [split $h .] {list +$c*2**[incr e -8]}]}

Try it online!

\$\endgroup\$
1
2

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.