package main import ( `fmt` `log` "strconv" ) const ( /* This is a nonsensical example. */ fragBits string = "0101010101000100" // [0101 0101 0100 0100], or 21828 (0x5544) ) var ( fragOffset uint16 = 0x000d // 13 fragFlagMask uint16 = 0x07 // 0b0000111 to mask 3 bits fragOffsetMask uint16 = 0x1fff // 8191, a 13-bit mask ) func ToFrag(flags, fo uint16) (frag uint16) { frag = (flags << fragOffset) | (fo & fragOffsetMask) return } func FromFrag(frag uint16) (flags, fo uint16) { flags = (frag >> fragOffset) & fragFlagMask fo = frag & fragOffsetMask return } func main() { var err error var u64 uint64 var frag uint16 var flags uint16 var fo uint16 // Given a fragmentation configuration of fragBits (see const at top)... if u64, err = strconv.ParseUint(fragBits, 2, 16); err != nil { log.Panicln(err) } frag = uint16(u64) // Prints: /* Frag is: 21828 (0x5544) */ fmt.Printf("Frag is:\t\t%d (%#04x)\n", frag, frag) flags, fo = FromFrag(frag) // Prints: /* Flags: 2 (0x0002) Fragmentation Offset: 5444 (0x1544) */ fmt.Printf( "Flags:\t\t\t%d (%#04x)\n"+ "Fragmentation Offset:\t%d (%#04x)\n", flags, flags, fo, fo, ) frag = ToFrag(flags, fo) // Prints: /* Confirmed Frag: 21828 (0x5544) */ fmt.Printf("Confirmed Frag:\t\t%d (%#02x)\n", frag, frag) }