| Bytes | Lang | Time | Link |
|---|---|---|---|
| 027 | Bash | 231106T215946Z | ShadowRa |
| 045 | Python 3.11+ no eval/builtin libraries | 231106T230348Z | ShadowRa |
| nan | 251015T152438Z | RARE Kpo | |
| nan | Uiua | 251010T100634Z | ojdo |
| 071 | Tcl | 251014T095121Z | sergiol |
| 030 | WhatLang | 251014T092338Z | YufangIG |
| 020 | x8616 machine code | 251009T201633Z | 640KB |
| 006 | Vyxal 3 | 251010T150652Z | Weird Gl |
| 063 | Python 3 | 251010T042300Z | Random D |
| 035 | Nibbles | 251009T214712Z | Adam |
| 010 | K ngn/k | 231106T221352Z | coltim |
| 005 | Thunno 2 | 230714T091914Z | The Thon |
| 266 | Pinecone | 210422T163713Z | wasif |
| nan | Pxem | 210416T122238Z | user1004 |
| 046 | Bash | 150325T142238Z | F. Hauri |
| 053 | min | 181122T131038Z | Panda0nE |
| 004 | Japt | 181115T111520Z | Shaggy |
| 050 | Kotlin | 181116T170905Z | snail_ |
| 011 | Burlesque | 181115T105907Z | mroman |
| 006 | Jelly | 181115T102048Z | Bubbler |
| 083 | Java 8 | 181114T014513Z | NotBaal |
| 032 | APLNARS | 181113T103426Z | user5898 |
| 033 | C gcc m32 / POSIX | 181112T220259Z | nwellnho |
| 021 | J | 181112T195743Z | Jonah |
| 016 | Perl 6 | 181112T214729Z | nwellnho |
| 013 | Jelly | 181112T214702Z | sporkl |
| 005 | 05AB1E | 181112T202239Z | hakr14 |
| 009 | Stax | 181112T200911Z | recursiv |
| 043 | Powershell | 181112T191754Z | mazzy |
| 047 | AWK in ~47 chars | 150325T144644Z | Blair Wy |
| 053 | Mathematica | 131020T150521Z | alephalp |
| 045 | JavaScript | 110202T215506Z | PleaseSt |
| 077 | C# – | 120926T145000Z | Mormegil |
| 014 | Haskell | 120924T165000Z | quasimod |
| 067 | Python No eval | 120924T010352Z | Kevin Br |
| 014 | Perl | 120922T201411Z | Grimmy |
| 040 | Ruby | 120226T155459Z | jsvnm |
| nan | 120301T233257Z | ardnew | |
| 059 | Scala | 120301T211336Z | user unk |
| 091 | C | 120301T061417Z | marinus |
| 485 | ASM 98 byte executable WinXP command shell | 120228T174717Z | Skizz |
| 079 | C | 110215T132221Z | Nim |
| 053 | Powershell | 120226T181054Z | Spelling |
| 047 | Ruby no builtins/eval | 110215T144229Z | Arnaud L |
| 054 | PHP no builtins/eval | 110215T145329Z | Arnaud L |
| 061 | PowerShell | 110210T005754Z | Ty Auvil |
| 022 | Befunge 2x11 = | 110204T122611Z | Nemo157 |
| 016 | Golfscript | 110206T191927Z | Nabb |
| 040 | Perl DIY for oneliners. | 110204T073240Z | Kent Fre |
| 069 | Python 3.2 | 110204T000322Z | l0nwlf |
| 021 | PHP 21 Characters | 110203T212909Z | ircmaxel |
| 020 | MySQL 20 Characters | 110203T212515Z | ircmaxel |
| 084 | D 84 Characters | 110203T030900Z | Jonathan |
| 036 | Befunge93 | 110202T223600Z | MiffTheF |
| nan | C++ lots of chars | 110202T155100Z | grokus |
| 120 | C# 120 Characters | 110202T102937Z | Kyle Ros |
| 045 | Python | 110202T124210Z | Alexandr |
| 070 | Windows PowerShell | 110202T114612Z | Joey |
| 021 | Golfscript | 110202T104030Z | gnibbler |
| 046 | Ruby | 110202T103128Z | gnibbler |
Bash, 27 bytes
echo $[${1//./<<32-++i*8|}]
At the cost of 1 character, this can avoid depending on the state of i:
Bash, 28 bytes
echo $[i=4,${1//./<<--i*8|}]
Dramatic improvement on existing bash solution (46 characters at time of writing).
Python 3.11+ (no eval/built-in libraries), 47 45 bytes
lambda x:0 .from_bytes(map(int,x.split('.')))
As of 3.11, int.from_bytes implicitly uses big-endian byte order. 0. from_bytes is shorter than int.from_bytes, and works just fine (since from_bytes is a class method, it works the same when called on an instance; the space is needed to avoid 0. being interpreted as a float).
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.
Uiua, 33 27 24 bytes
⌝⊥256⇌⊜⋕≠@..
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!)
Tcl, 71 bytes
proc C {h e\ 32} {expr [lmap c [split $h .] {list +$c*2**[incr e -8]}]}
x86-16 machine code, 20 bytes
00000000: 4132 e4ac 2c30 7206 d50a 8ae0 e2f5 8ac4 A2..,0r.........
00000010: aae2 eec3 ....
Callable real mode function, custom calling convention: DS:[SI] = Input ASCIIZ string, CX = Input string length, ES:[DI] = caller provided DWORD output buffer (big endian).
0000 IPBIN:
0000 41 INC CX ; set length + 1 for end condition
0001 NEXT_OCTET:
0001 32 E4 XOR AH, AH ; clear running octet sum
0003 CHAR_LOOP: ; convert octet decimal string to byte
0003 AC LODSB ; AL = next char
0004 2C 30 SUB AL, '0' ; convert to ASCII
0006 72 06 JB NEXT_CHAR ; check for end of octet (non-digit)
0008 D5 0A AAD ; AL = AL + ( AH * 10 )
000A 8A E0 MOV AH, AL ; save to running sum
000C E2 F5 LOOP CHAR_LOOP ; loop until non-digit or end of input
000E NEXT_CHAR:
000E 8A C4 MOV AL, AH ; AL = last converted octet
0010 AA STOSB ; write to caller output buffer
0011 E2 EE LOOP NEXT_OCTET
0013 C3 RET ; return to caller
Example output from test program:
Vyxal 3, 6 bytes
'.s⌊⑦⊣
Well this was easier than I thought...
'.s⌊⑦⊣
'.s⌊ # Split on . and convert to integers
⑦⊣ # Base 256
💎
Created with the help of Luminespire.
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).
Nibbles, 3.5 bytes
`@256_
Explanation
`@256_
_ Read all numbers from STDIN (ignoring the periods)
`@ Convert from base
256 256
K (ngn/k), 10 bytes
256/.'"."\
"."\split string input on.'s.'convert each string to its integer256/convert from base-256
Thunno 2, 5 bytes
'./ɠḋ
Explanation
'./ɠḋ '# Implicit input
'./ '# Split it on "."s
ɠḋ # Convert from base-256
# Implicit output
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)
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.
Bash - 46
Table of content
You will find 4 differently golfed version:
echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0] # 46chr set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4] # 47chr v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v] # 65chr mapfile -td. i<<<$1;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o # 68chr
New version! 2018-11-15 More golfed, 46 char
echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]
Explanation
- I used
$_for more golfing. - Syntax
${1//./ }will substitute every dots.by spaces. - so
printfwill render something like192<<(_-=8)|168<<(_-=8)|1<<(_-=8)|1<<(_-=8)| - then we will add a
0after last OR|and - preset
_to 32. bash will read construct from left to right, so$((_-=8))make24at 1st shift,16on second, and so on.
in action:
set -- 192.168.1.1
echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]
3232235777
For fun: trying to get $_ content, after this:
echo $_ 3232235777;-b
set -- 192.168.1.1 echo $_ $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0] $_ 192.168.1.1 3232235777 0Ok, that's correct
32 - 4 x 8 = 0
In a function:
ip2int() {
echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]
}
ip2int 192.168.1.1
3232235777
ip2int 255.255.255.255
4294967295
ip2int 0.0.0.0
0
or into a loop: -> 60
ip2int() {
for i;do
echo $[_=32,`printf "%d<<(_-=8)|" ${i//./ }`0]
done
}
ip2int 192.168.1.1 10.10.104.36 8.8.8.8 1.1.1.1 255.255.255.255 0.0.0.0
3232235777
168454180
134744072
16843009
4294967295
0
bash (v4.1+): 47
First post
set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4]
Explanation:
- Syntax
${1//./ }will substitute every dots.by spaces. set --set positional parameters ($@=($1 $2 $3...))- So
set -- ${1//./ }will split$1by dots and set$1,$2,$3and$4if string containg3dots (and no spaces).
in action:
set -- 192.168.1.1
set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4]
3232235777
or in a function:
ip2int() {
set -- ${1//./ }
echo $[$1<<24|$2<<16|$3<<8|$4]
}
ip2int 192.168.1.1
3232235777
ip2int 0.0.0.0
0
or into a loop: -> 61
for i;do set -- ${i//./ };echo $[$1<<24|$2<<16|$3<<8|$4];done
in action:
ip2int() {
for i;do
set -- ${i//./ }
echo $[$1<<24|$2<<16|$3<<8|$4]
done
}
ip2int 192.168.1.1 10.10.104.36 8.8.8.8 1.1.1.1 0.0.0.0
3232235777
168454180
134744072
16843009
0
Another version differently golfed: 65
v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v]
Sample:
ip2int() {
v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v]
}
ip2int 255.255.255.255
4294967295
ip2int 10.10.104.36
168454180
In a loop (+14): 82
ip2int() {
for i;do
v=('|%d<<'{24,16,8,0})
printf -vv "${v[*]}" ${1//./ }
echo $[0$v]
done
}
* or a little more ugly: 70*
v=('|%d<<'{24,16,8});printf -vv "${v[*]}" ${1//./ };echo $[0${v%<<2*}]
where printf give some string like |192<<24 |168<<16 |1<<8|1<<24 |0<<16 |0<<8 we have to cut at last <<2....
golfed with mapfile, longer: 68
ip2int() {
mapfile -td. i<<<$1;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o
}
or with loop: 82
ip2int() {
for a;do
mapfile -td. i<<<$a;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o
done
}
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.
Japt, 10 4 bytes
nG²o
G :16
² :Squared
o :Range [0,G²)
n :Convert input string from that base to base-10 integer
Burlesque - 11 bytes
'.;;ri256ug
'.;; split by `.`
ri read integer
256ug undigits base 256
Jelly, 6 bytes
ṣ”.Vḅ⁹
How it works
ṣ”.Vḅ⁹ Main link (monad). Input: string
ṣ”. Split at dots
V Convert to numbers
ḅ⁹ Convert base 256 to integer
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;}
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.
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
C (gcc) -m32 / POSIX, 33 bytes
f(a){inet_aton(a,&a);a=ntohl(a);}
On a big-endian platform, you could simply define a macro with -Df=inet_aton for 13 bytes.
J, 21 bytes
[:256&#.[:".;._1'.'&,
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
Jelly, 13 bytes
4Ḷ⁹*U
ṣ”.V×¢S
I don't think Jelly has a builtin for this. At least, I couldn't find one.
Powershell, 47 43 bytes
$args-split'\.'|%{$r=([long]$r-shl8)+$_};$r
Test script:
$f = {
$args-split'\.'|%{$r=([long]$r-shl8)+$_};$r
}
@(
,("192.168.1.1",3232235777)
,("10.10.104.36",168454180)
,("8.8.8.8",134744072)
) | % {
$s,$expected = $_
$result = &$f $s
"$($result-eq$expected): $result"
}
Output:
True: 3232235777
True: 168454180
True: 134744072
AWK in ~47 chars
First-timer here... Um, not sure how to count this, but without the 'echo' it's 47 chars in AWK. (Not exactly bogey golf, but it's in the hole.)
echo $addr | /bin/awk -F\. '{print $1*16777216+$2*65536+$3*256+$4}'
Full day early for #tbt, too, so I actually met a schedule!!! *8-)
Banner day.
Mathematica, 53 chars
f=FromDigits;f[f/@StringSplit[InputString[],"."],256]
JavaScript (45 characters)
Requires support for the .reduce() Array method introduced in ES5 and arrow functions.
f=(x)=>x.split('.').reduce((p,c)=>p<<8|c)>>>0
C# – 77 chars
Func<string,uint>F=s=>s.Split('.').Aggregate(0u,(c,b)=>(c<<8)+uint.Parse(b));
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.
Python (No eval) - 67
c=lambda x:long(''.join(["%02X"%long(i) for i in x.split('.')]),16)
Perl, 14 characters:
sub _{unpack'L>',pop}
# Example usage
print _(10.10.104.36) # prints 168454180
Ruby (40)
q=->x{x.gsub(/(\d+)\.?/){'%02x'%$1}.hex}
->
q["192.168.1.1"]
=> 3232235777
Perl with builtins (35):
unpack"N",pack"C4",split/\./,shift;
Perl without builtins (42):
split/\./,shift;$s+=$_<<@_*8while$_=shift;
Scala 59 chars:
def f(i:String)=(0L/:i.split("\\.").map(_.toInt))(_*256+_)
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);}
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
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 :)
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.
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
PHP (no builtins/eval) - 54
<foreach(explode(".",$argv[1])as$b)$a=@$a<<8|$b;echo$a;
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
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.
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).
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}
Python 3.2 (69)
sum((int(j)*4**(4*i)) for i,j in enumerate(input().split('.')[::-1]))
PHP - 21 Characters
<?=ip2long($argv[1]);
MySQL - 20 Characters
SELECT INET_ATON(s);
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;
}
Befunge-93 - 36 characters
&"~"2+::8****&884**:**&884***&++++.@
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;
}
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 ;)
Python 56 45
c=lambda x:eval('((('+x.replace('.','<<8)+'))
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
Golfscript - 21 chars
{'.'/{~}%{\256*+}*}:f
Ruby - 46 chars
require"ipaddr"
def f s;IPAddr.new(s).to_i;end
