Converts a 32-bit unsigned integer i to a string representation of an IP address

Converts a 32-bit unsigned integer i to a string representation of an IP address

Assume that the value of i is 2130706433, which is expressed in binary as 10000000 00000001 00000001 00000001.

According to the calculation process of the code, the result string is "129.1.1.128".

Specific steps are as follows:

  1. (i & 0xFF) means taking the lowest 8 bits of i, which is 00000001, and converting it to decimal 1.
  2. ((i >> 8) & 0xFF) means shifting i right by 8 bits to get 10000000, then taking the lowest 8 bits, which is 00000000, and converting it to decimal 0.
  3. ((i >> 16) & 0xFF) means shifting i to the right by 16 bits to get 100000, then taking the lowest 8 bits, which is 00000001, and converting it to decimal 1.
  4. ((i >> 24) & 0xFF) means shifting i right by 24 bits to get 1, then taking the lowest 8 bits, which is 00000001, and converting it to decimal 1.

By connecting these four items separated by ".", you get "129.1.1.128".

Hope this answer helps you all.


    public static String getWifiIp(Context context) {
        WifiManager wifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifimanager.getConnectionInfo();
        if (wifiInfo != null) {
            return intToIp(wifiInfo.getIpAddress());
        }
        return null;
    }

    /**
     * 这段代码将一个32位无符号整数i转换为IP地址的字符串表示。
     * 假设i的值为2130706433,以二进制表示为 10000000 00000001 00000001 00000001。
     * 
     * 按照代码的计算过程,结果字符串为 "129.1.1.128"。
     * 
     * 具体步骤如下:
     * (i & 0xFF) 表示取i的最低8位,即 00000001,转换为十进制为1。
     * ((i >> 8) & 0xFF) 表示将i右移8位,得到 10000000,再取最低8位,即 00000000,转换为十进制为0。
     * ((i >> 16) & 0xFF) 表示将i右移16位,得到 100000,再取最低8位,即 00000001,转换为十进制为1。
     * ((i >> 24) & 0xFF) 表示将i右移24位,得到 1,再取最低8位,即 00000001,转换为十进制为1。
     *
     * 将这四项以"."分隔连接起来,就得到了 "129.1.1.128"。
     * @param i
     * @return
     */
    private static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }

Guess you like

Origin blog.csdn.net/ck3345143/article/details/132444415