1. String to integer
first step:
- Yes to determine whether the string is a legitimate IPv4 address.
- If it is legal, it will be converted into a character array ([]byte).
Step 2:
- The above character array is written into the ret variable in a large-endiment manner using the method.
func InetAddr(ipaddr string) uint32 { var ret uint32 ip := (ipaddr) if ip == nil { return 0 } if err := ((ip.To4()), , &ret); err != nil { return 0 } return ret }
2. Integer to string
Integer conversion to strings is simpler.
To demonstrate with an example:
There is an IPv4 address hexadecimal integer representation of 0x01020304, which is shifted 24, 16, 8, and 0 respectively.
You will get 4 segments of the IP address string representation:
byte(0x01020304 >> 24) = byte(0x01) = 1
byte(0x01020304 >> 16) = byte(0x0102) = 2
byte(0x01020304 >> 8) = byte(0x010203) = 3
byte(0x01020304 >> 0) = byte(0x01020304) = 4
After splicing these four values with ., you can get the string table: 1.2.3.4
func IPv4Uint32ToString(ip uint32) string { return ("%d.%d.%d.%d", byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip)) }
Notice:
byte overflows when casting is greater than its stored maximum (0xff), and the left part will be discarded.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.