gpt4 book ai didi

java - 无法理解如何在 Android 和 Java 中将整数转换为 IP

转载 作者:可可西里 更新时间:2023-11-01 02:45:21 25 4
gpt4 key购买 nike

我正在为我的 Android 手机构建一个小应用程序。我的背景不是计算机科学但我熟悉C/C++和一些开发概念。现在我试图显示 IP 地址我的电话。根据 Android 引用,我使用了返回的 getIpAddress() 方法一个整数。

然后查看 stackoverflow 我看到了这里发布的解决方案: Android IP address with javaPaul Ferguson 发布,我将其复制到这里:

String ipString = String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));

ip 是一个包含 ip 地址的 int 类型的变量。任何人都可以向我解释这是如何工作的吗?请注意,我的 Java 技能非常入门。

感谢@Joop Eggen 的评论 让我们假设我们有一个整数 -926414400 的 ip 地址 下面是代码的工作原理:

IP fileds  <1> . <2> . <3> . <4>

everything is done using the bitwise (and) operation this
means that all operations are made vertically bit by bit

field <1>

ipint = 11001000 11001000 00001001 11000000
0xff = 00000000 00000000 00000000 11111111
------------------------------------
<1> = 00000000 00000000 00000000 11000000

which is equal to 192

Field <2> first we do a shift by 8 bits since
the >> operator takes precedence over the & operator
same for fields <3> and <4>

shift by 8 bits ipint now becomes

ipint = 00000000 11001000 11001000 00001001
0xff = 00000000 00000000 00000000 11111111
------------------------------------
<2> = 00000000 00000000 00000000 00001001

which is equal to 9

For field <3> shift by 16 bits ipint becomes

ipint = 00000000 00000000 11001000 11001000
0xff = 00000000 00000000 00000000 11111111
------------------------------------
<3> = 00000000 00000000 00000000 11001000

which is 200


For field <4> shift by 24 bits ipint becomes

ipint = 00000000 00000000 00000000 11001000
0xff = 00000000 00000000 00000000 11111111
------------------------------------
<4> = 00000000 00000000 00000000 11001000

which is 200

So the ip is 192.9.200.200

最佳答案

有两个标准,IP v4使用 4 个字节,较新的仍然不太广泛传播 IP v6有更多的字节。

现在在您的 IP v4 情况下,4 个字节可能包含一个 Java 整数或只是列出的每个字节。

顺便说一句,URL 可以将 IP 号用作 4 字节值或一个整数:

http://3232235778/
http://210.43.98.51/

(我没有转换或检查数字。)

代码使用了一个技巧,将 int 转换为 long,因为 java 整数是有符号的;最左边的位为 1 并不意味着很大的数字,而是负数。

取出4个字节,每字节8位,屏蔽后右移。其中 0xFF 在 16 进制中为 FF,在 10 进制中为 255,在 2 进制中为 0b11111111 或 11111111。

有一个位运算&(“与”),其实就是乘法(模2)。

x  y  x&y  x|y
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

现在有一些位 abcdefgh 并且你只想检查位 def 你会这样做:

abcdefgh & 00011100 = 000def00 = def00   (00011100 is called a mask)
(abcdefgh & 00011100) >> 2 = def (shift right 2)

关于java - 无法理解如何在 Android 和 Java 中将整数转换为 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27170602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com