I recently learned that converting IP addresses into decimal, octal, and hexadecimal can also access the website.
Convert IP to digital (the second algorithm. Use left shift, bitwise or implementation. More efficient.):
public long ipToLong(String ipAddress) { long result = 0; String[] ipAddressInArray = ("\\."); for (int i = 3; i >= 0; i--) { long ip = (ipAddressInArray[3 - i]); //left shifting 24,16,8,0 and bitwise OR //1. 192 << 24 //1. 168 << 16 //1. 1 << 8 //1. 2 << 0 result |= ip << (i * 8); } return result; }
When numbers are converted to IP, both algorithms are similar:
//ip = 3232235778 public String longToIp(long ip) { StringBuilder result = new StringBuilder(15); for (int i = 0; i < 4; i++) { (0,(ip & 0xff)); if (i < 3) { (0,'.'); } ip = ip >> 8; } return (); } //ip = 3232235778 public String longToIp2(long ip) { return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + (ip & 0xFF); }
Complete code:
public class JavaBitwiseExample { public static void main(String[] args) { JavaBitwiseExample obj = new JavaBitwiseExample(); ("iptoLong : " + ("192.168.1.2")); ("iptoLong2 : " + obj.ipToLong2("192.168.1.2")); ("longToIp : " + (3232235778L)); ("longToIp2 : " + obj.longToIp2(3232235778L)); } // example : 192.168.1.2 public long ipToLong(String ipAddress) { // ipAddressInArray[0] = 192 String[] ipAddressInArray = ("\\."); long result = 0; for (int i = 0; i < ; i++) { int power = 3 - i; int ip = (ipAddressInArray[i]); // 1. 192 * 256^3 // 2. 168 * 256^2 // 3. 1 * 256^1 // 4. 2 * 256^0 result += ip * (256, power); } return result; } public long ipToLong2(String ipAddress) { long result = 0; String[] ipAddressInArray = ("\\."); for (int i = 3; i >= 0; i--) { long ip = (ipAddressInArray[3 - i]); // left shifting 24,16,8,0 and bitwise OR // 1. 192 << 24 // 1. 168 << 16 // 1. 1 << 8 // 1. 2 << 0 result |= ip << (i * 8); } return result; } public String longToIp(long i) { return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + (i & 0xFF); } public String longToIp2(long ip) { StringBuilder sb = new StringBuilder(15); for (int i = 0; i < 4; i++) { // 1. 2 // 2. 1 // 3. 168 // 4. 192 (0, (ip & 0xff)); if (i < 3) { (0, '.'); } // 1. 192.168.1.2 // 2. 192.168.1 // 3. 192.168 // 4. 192 ip = ip >> 8; } return (); } }
Summarize
The above is all the content of this article about the code conversion examples of Java programming IP addresses and numbers. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out!