Cannot understand how to convert integer to IP in Android and Java -
i building small application android phone. background in not on computer science familiar c/c++ , development concepts. trying display ip address of phone. , according android references used getipaddress()
method returns integer.
then looking in stackoverflow saw solution posted here: android ip address java posted paul ferguson
, copying here:
string ipstring = string.format( "%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff));
the ip
variable of type int
contains ip address. can please explain me how works? note java skills quite introductory.
thanks comments @joop eggen lets have ip address integer of -926414400
here how code works:
ip fileds <1> . <2> . <3> . <4> done using bitwise (and) operation means operations made vertically bit bit field <1> ipint = 11001000 11001000 00001001 11000000 0xff = 00000000 00000000 00000000 11111111 ------------------------------------ <1> = 00000000 00000000 00000000 11000000 equal 192 field <2> first shift 8 bits since >> operator takes precedence on & operator same fields <3> , <4> shift 8 bits ipint becomes ipint = 00000000 11001000 11001000 00001001 0xff = 00000000 00000000 00000000 11111111 ------------------------------------ <2> = 00000000 00000000 00000000 00001001 equal 9 field <3> shift 16 bits ipint becomes ipint = 00000000 00000000 11001000 11001000 0xff = 00000000 00000000 00000000 11111111 ------------------------------------ <3> = 00000000 00000000 00000000 11001000 200 field <4> shift 24 bits ipint becomes ipint = 00000000 00000000 00000000 11001000 0xff = 00000000 00000000 00000000 11111111 ------------------------------------ <4> = 00000000 00000000 00000000 11001000 200 ip 192.9.200.200
there 2 standards, ip v4 using 4 bytes, , newer still not wide spread ip v6 more bytes.
now in ip v4 case, 4 bytes may comprise java integer or every byte listed.
by way urls may use ip number both 4 byte values, or 1 single integer:
http://3232235778/ http://210.43.98.51/
(i did not convert or check numbers.)
the code uses trick, converting int long, java integers signed; left-most bit being 1 not mean high number, negative.
to take out 4 bytes, every byte 8 bits, masked , shifted right. 0xff ff in base 16, 255 in base 10, 0b11111111 or 11111111 in base 2.
there bit operation & ("and") in fact multiplication (modulo 2).
x y x&y x|y 0 0 0 0 0 1 0 1 1 0 0 1 1 1 1 1
now having bits abcdefgh
, want inspect bits def
do:
abcdefgh & 00011100 = 000def00 = def00 (00011100 called mask) (abcdefgh & 00011100) >> 2 = def (shift right 2)
Comments
Post a Comment