go - Converting integer in reverse order to gererate IP in reverse order -
i wanted generate ip in reverse order.
functionality generate ip address follow:
val := 1<<(32-prefixlen) // let take prefixlen 24 ip4(val) = ip4(256) = 0.0.1.0
i wanted ip in reverse order i.e., 0.1.0.0
, convert val
in reverse order bytes , send ip4()
function.
functionality have tried resulted in integer overflow:
temp1:=byte(val*0xff<<24) temp2:=byte(val*0xff00<<16) temp3:=byte(val*0xff0000<<8) temp4:=byte(val*0xff000000) valreverse := uint32(temp4)|uint32(temp3)|uint32(temp2)|uint32(temp1) ip4(valreverse)=0.1.0.0 //expected
reversing bytes
first, have use uint32
type instead of byte
byte
value has 8 bits (bit positions above 8 don't exist).
next, have use bitwise , &
, not multiplication *
.
third, shift values incorrect. see working example:
prefixlen := uint32(24) var val uint32 val = 1 << (32 - prefixlen) fmt.printf("%08x\n", val) temp1 := uint32(val & 0xff << 24) temp2 := uint32(val & 0xff00 << 8) temp3 := uint32(val & 0xff0000 >> 8) temp4 := uint32(val & 0xff000000 >> 24) valreverse := uint32(temp4) | uint32(temp3) | uint32(temp2) | uint32(temp1) fmt.printf("%08x\n", valreverse)
output (try on go playground):
00000100 00010000
but use net.ip
type models ip address byte slice, , using can reverse bytes slice-reversing algorithm.
this how like:
ip := net.ipv4(0, 0, 1, 0).to4() fmt.println(ip) // reverse: i, j := 0, len(ip)-1; < j; i, j = i+1, j-1 { ip[i], ip[j] = ip[j], ip[i] } fmt.println(ip)
output (try on go playground):
0.0.1.0 0.1.0.0
note: if have ip value of uint32
, can still use net.ip
type, creating net.ip
value this:
ip := net.ipv4(byte(val>>24), byte(val>>16), byte(val>>8), byte(val)).to4()
reversing bits
if want reverse bits, have bit-by-bit. 1 possible solution this:
prefixlen := uint32(24) var val uint32 val = 1 << (32 - prefixlen) fmt.printf("%08x\n", val) var valreverse uint32 := 0; < 32; i, val = i+1, val>>1 { valreverse = valreverse<<1 | val&0x01 } fmt.printf("%08x\n", valreverse)
output (try on go playground):
00000100 00800000
an alternative, maybe more complex way reverse bits:
var valreverse uint32 mask1, mask2 := uint32(0x01), uint32(0x80000000); mask2 != 0; mask1, mask2 = mask1<<1, mask2>>1 { if val&mask1 != 0 { valreverse |= mask2 } }
output same, try variant on go playground.
Comments
Post a Comment