Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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

To change an IPv4 address to it's integer representation, the following calculation is required:

  • Break the IP address into it's 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
share|improve this question
1  
I think this would be better if there was a restriction in place prohibiting a language's built-in functions. – Nathan Osman Feb 6 '11 at 20:04
@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. – Kyle Rozendo Feb 7 '11 at 5:51

29 Answers

PHP - 21 Characters

<?=ip2long($argv[1]);
share|improve this answer

Ruby (no builtins/eval) - 47

s=->s{s.split(".").inject(0){|a,b|a<<8|b.to_i}}

Test:

s["192.168.1.1"]
3232235777
share|improve this answer

C: 79 characters

main(i,a)char**a;{i=i<<8|strtol(a[1],a+1,0);*a[1]++?main(i,a):printf("%u",i);}

EDIT: removed C++, would not compile without headers; with GCC, the printf and strtol function calls trigger built-in functions, hence headers can be skipped. Thx to @ugoren for the tips. This will compile as is without additional options to gcc.

EDIT2: return is actually redundant :)

share|improve this answer
very clever use of main() :) .. my version was 116bytes. – akira Feb 15 '11 at 14:21
I get a segmentation fault. – Nathan Osman Feb 19 '11 at 3:11
@George, what is your input and how are you running it? – Nim Feb 21 '11 at 10:43
I'm running it with my UserScript through codepad.org – Nathan Osman Feb 21 '11 at 19:33
This won't work in C++, you can't call main recursively. – Bunnit Feb 26 '12 at 17:40
show 5 more comments

MySQL - 20 Characters

SELECT INET_ATON(s);
share|improve this answer

Golfscript -- 16 chars

{[~]2%256base}:f

As a standalone program, this is even shorter at 11.

~]2%256base

Extremely straightforward. Evaluates the input string (~) and puts it into an array []. Since the .s in the string duplicate the top of the stack, we only take every other term in the array (2%). We now have an array which basically represents a base 256 number, so we use a built-in function to do the conversion. (256base).

share|improve this answer
very clever. i guess base256 is treated differently to say base10 or base16 then where 48=>0? – gnibbler Feb 6 '11 at 20:05
@gnibbler: I'm not sure what you're suggesting -- the base function handles all bases the same way, e.g. {:B;{\B*+}*}:base (although the real function is overloaded for conversions the other way). Interesting to note is that base conversion for strings is the same as arrays (as strings are just arrays without nesting, but with a different output format). – Nabb Feb 6 '11 at 20:27
yeah i was thinking of base conversions of strings, so i didn't look closely enough at base for my answer – gnibbler Feb 7 '11 at 0:20
Very clever. Now do that for an IPv6 address. :) – Ilmari Karonen Feb 29 '12 at 17:28

Befunge - 2x11 = 22 characters

So close, Befunge will win one day.

>&+~1+#v_.@
^*4*8*8<

Explanation

The biggest distinguishing feature of Befunge is that instead of being a linear set of instructions like most languages; it is a 2d grid of single character instructions, where control can flow in any direction.

>      v
^      <

These characters change the direction of control when they are hit, this makes the main loop.

 &+~1+

This inputs a number and pushes it onto the stack (&), pops the top two values off the stack, adds them and pushes them back onto the stack (+), inputs a single character and places its ascii value on the stack (~), then pushes 1 onto the stack and adds them (1+).

The interpreter I've been using returns -1 for end of input, some return 0 instead so the 1+ part could be removed for them.

      #v_.@

The # causes the next character to be skipped, then the _ pops a value off the stack and if it is zero sends control right, otherwise sends it left. If the value was zero . pops a value off the stack and outputs it as an integer and @ stops the program. Otherwise v sends control down to the return loop.

^*4*8*8<

This simply multiplies the top value of the stack by 256 and returns control to the start.

share|improve this answer
Pardon my ignorance, but should that be 19 chars? I understand why you say 2x11, but why does it work that way? – Kyle Rozendo Feb 4 '11 at 19:08
Befunge is a 2d language, if you look for the >v<^ that is actually the main loop in this program. I guess in this case control doesn't actually pass through those last 3 spaces on the bottom, but I find it easiest to just count Befunge programs as the smallest bounding rectangle; and if you were to try and count control flow you get into trouble with self-modifying programs. – Nemo157 Feb 4 '11 at 22:37

Ruby - 46 chars

require"ipaddr"
def f s;IPAddr.new(s).to_i;end
share|improve this answer
I think that constitutes cheating. ;-) – Chris Jester-Young Feb 2 '11 at 12:10

Ruby (40)

q=->x{x.gsub(/(\d+)\.?/){'%02x'%$1}.hex}

->

q["192.168.1.1"]
=> 3232235777
share|improve this answer
Nice idea of using regexp. – Łukasz Niemier Feb 28 '12 at 14:56
Very clever! Also you can write to_i 16 as hex to save some characters. – chron Mar 1 '12 at 21:54
thanks @chron that made both this and link 4 characters shorter – jsvnm Mar 2 '12 at 8:35

Golfscript - 21 chars

{'.'/{~}%{\256*+}*}:f
share|improve this answer
+1 Good solid solution. Don't you wish GolfScript provides bit-shifting operators? ;-) (Though, darned if I know which symbols they should be bound to.) – Chris Jester-Young Feb 2 '11 at 12:12

Python 56 45

c=lambda x:eval('((('+x.replace('.','<<8)+'))
share|improve this answer

C++ - lots of chars

#include <boost/algorithm/string.hpp>
#include <string>
#include <vector>
uint f(std::string p)
{
        std::vector<std::string> x;
        boost::split(x,p,boost::is_any_of("."));
        uint r=0;
        for (uint i = 0; i < x.size(); i++)
                r=r*256+atoi(x[i].c_str());
        return r;
}
share|improve this answer
+1 for using Boost. – Nathan Osman Feb 6 '11 at 20:37
@George Edison: using boost helps to get down with the numbers of chars? :) – akira Feb 15 '11 at 14:24

PowerShell 66 61

Variation on Joey's answer:

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

PS C:\> '192.168.1.1' | I
3232235777
PS C:\> '10.10.104.36' | I
168454180
PS C:\> '8.8.8.8' | I
134744072
share|improve this answer
Argh, I must have been stupid to have missed that ... – Joey Feb 15 '11 at 1:59

Windows PowerShell, 70

Naïve approach:

filter I{[int[]]$x=$_-split'\.'
$x[0]*16MB+$x[1]*64KB+$x[2]*256+$x[3]}

With using System.Net.IPAddress: 76

filter I{([ipaddress]($_-replace('(.+)\.'*3+'(.+)'),'$4.$3.$2.$1')).address}

Test:

> '192.168.1.1'|I
3232235777
share|improve this answer

JavaScript (53/57 characters)

57 characters: This will work in Firefox only, as it uses the .reduce() Array method introduced in ES5 and Mozilla's proprietary "expression closure" feature.

function f(x)x.split('.').reduce(function(p,c)p<<8|c)>>>0

Alexandru's "eval" approach saves four characters:

function f(x)eval('((('+x.replace(/\./g,'<<8)+'))>>>0
share|improve this answer

Befunge-93 - 36 characters

&"~"2+::8****&884**:**&884***&++++.@
share|improve this answer

Perl : DIY ( for oneliners. )(40)

$j=3;$i+=($_<<($j--*8))for split/\./,$x;

# Use value in $i

DIY Function(65):

sub atoi{my($i,$j)=(0,3);$i+=($_<<($j--*8))for split'.',shift;$i}
share|improve this answer
You can split by a string, so you save a character by using split'.' rather than split/\./ – Charlie Somerville Feb 5 '11 at 10:14
With the function version, yes, but the inline version no, because you'd need split q{.} to get around the need to escape shell quotes :/ – Kent Fredric Feb 6 '11 at 4:59
@Kent: Use split "." then. (And if the entire line was double-quoted, you would have to escape every $i and $j as well.) – grawity Sep 25 '12 at 20:10

C# - 120 Characters

float s(string i){var o=i.Split('.').Select(n=>float.Parse(n)).ToList();return 16777216*o[0]+65536*o[1]+256*o[2]+o[3];}

My first code golf - be gentle ;)

share|improve this answer
You can remove the spaces around your first '='. However, your main problem is int overflow ;). Remember, an IP address takes up 4 full bytes. – Nellius Feb 2 '11 at 10:49
@Nellius - quite right. I didn't even think of checking that, basically checked on compile. Thanks, will fix now. – Kyle Rozendo Feb 2 '11 at 12:35

D: 84 Characters

uint f(S)(S s)
{
    uint n;
    int i = 4;

    foreach(o; s.split("."))
        n += to!uint(o) << 8 * --i;

    return n;
}
share|improve this answer

Python 3.2 (69)

sum((int(j)*4**(4*i)) for i,j in enumerate(input().split('.')[::-1]))
share|improve this answer

PHP (no builtins/eval) - 54

<foreach(explode(".",$argv[1])as$b)$a=@$a<<8|$b;echo$a;
share|improve this answer
Shouldn't this open with <?php, not just <? – TRiG Sep 25 '12 at 16:44
@TRiG, I believe you can change the PHP opening delimiter in the config file. Useful in this case. – Xeoncross Sep 25 '12 at 16:56
@Xeoncross. Ah. Neat. I might try that one day, just to mess with my workmates' heads. – TRiG Sep 25 '12 at 16:57

Perl, 14 characters:

sub _{unpack'L>',pop}

# Example usage
print _(10.10.104.36) # prints 168454180
share|improve this answer
2  
How do you make that 14 characters? I count 21. – Peter Taylor Oct 3 '12 at 10:49

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.

share|improve this answer

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
share|improve this answer

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);}
share|improve this answer

Scala 59 chars:

def f(i:String)=(0L/:i.split("\\.").map(_.toInt))(_*256+_)
share|improve this answer

Perl with builtins (35):

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

Perl without builtins (42):

split/\./,shift;$s+=$_<<@_*8while$_=shift;
share|improve this answer

Python (No eval) - 67

c=lambda x:long(''.join(["%02X"%long(i) for i in x.split('.')]),16)
share|improve this answer
can you not shorten it a few more characters by using int() instead of long()? – Wug Sep 24 '12 at 6:58

Haskell - 14 chars

(.) a=(256*a+)

usage in GHCi:

Prelude> let (.) a=(256*a+)
Prelude> 192. 168. 0. 1
3232235521

The only problem is that you have to put spaces left or right of the dot, otherwise the numbers will be interpreted as floating point.

share|improve this answer

C# – 77 chars

Func<string,uint>F=s=>s.Split('.').Aggregate(0u,(c,b)=>(c<<8)+uint.Parse(b));
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.