74 lines
1.2 KiB
Go
74 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
`fmt`
|
|
`log`
|
|
"strconv"
|
|
)
|
|
|
|
const (
|
|
vihlBits string = "01000101" // [0100 0101], or 69 (0x45)
|
|
ipVer uint8 = 0x04 // 4; unused in this program, but represented for completion's sake.
|
|
)
|
|
|
|
var (
|
|
vihlLowerMask uint8 = 0x0f // 15
|
|
)
|
|
|
|
func ToVIHL(ver, ihl uint8) (vihl byte) {
|
|
|
|
// In Go, a byte is exactly equal to a uint8
|
|
// so type casting/conversion is unnecessary here.
|
|
vihl = (ver << 4) | (ihl & vihlLowerMask)
|
|
|
|
return
|
|
}
|
|
|
|
func FromVIHL(vihl byte) (ver, ihl uint8) {
|
|
|
|
ver = vihl >> 4
|
|
ihl = vihl & vihlLowerMask
|
|
|
|
return
|
|
}
|
|
|
|
func main() {
|
|
|
|
var err error
|
|
var u64 uint64
|
|
var vihl byte
|
|
var ver uint8
|
|
var ihl uint8
|
|
|
|
// Given a V/IHL of vihlBits (see const at top)...
|
|
if u64, err = strconv.ParseUint(vihlBits, 2, 8); err != nil {
|
|
log.Panicln(err)
|
|
}
|
|
vihl = uint8(u64)
|
|
// Prints:
|
|
/*
|
|
V/IHL is: 69 (0x45)
|
|
*/
|
|
fmt.Printf("V/IHL is:\t\t%d (%#02x)\n", vihl, vihl)
|
|
|
|
ver, ihl = FromVIHL(vihl)
|
|
// Prints:
|
|
/*
|
|
Version: 4 (0x04)
|
|
IHL: 5 (0x05)
|
|
*/
|
|
fmt.Printf(
|
|
"Version:\t\t%d (%#02x)\n"+
|
|
"IHL:\t\t\t%d (%#02x)\n",
|
|
ver, ver,
|
|
ihl, ihl,
|
|
)
|
|
|
|
vihl = ToVIHL(ver, ihl)
|
|
// Prints:
|
|
/*
|
|
Confirmed V/IHL: 69 (0x45)
|
|
*/
|
|
fmt.Printf("Confirmed V/IHL:\t%d (%#02x)\n", vihl, vihl)
|
|
}
|