Search code examples
datetimegosnmpgosnmpoctetstring

Converting datetime OctetString to human readable string in GoLang


How to convert Datetime Octetstring to ASCII. I read through one of the example in python netsnmp but still not able to solve it.

This is what I received from gosnmp as slice of []uint8

[7 224 1 28 20 5 42 0 43 0 0]

or Go-syntax representation of the value

[]byte{0x7, 0xe0, 0x1, 0x1c, 0x14, 0x4, 0x2a, 0x0, 0x2b, 0x0, 0x0}

And output in datetime should be something like this:

2015-10-7,17:23:27.0,+0:0

here is the mibs:oid: HOST-RESOURCES-MIB::hrSWInstalledDate

Can someone give me some idea on how to use binary to decode that into human readable ascii or strings.


Solution

  • The format is described here: Convert snmp octet string to human readable date format

    If you just need to create a date/time string in the format you mentioned, this will do it:

    func snmpTimeString(c []byte) string {
        year := (int(c[0]) << 8) | int(c[1])
        return fmt.Sprintf("%d-%d-%d,%02d:%02d:%02d.%d,%c%d:%d", year, c[2], c[3], c[4], c[5], c[6], c[7], c[8], c[9], c[10])
    }
    
    func main() {
        c := []byte{0x7, 0xe0, 0x1, 0x1c, 0x14, 0x4, 0x2a, 0x0, 0x2b, 0x0, 0x0}
        fmt.Println(snmpTimeString(c))
    }
    

    See https://play.golang.org/p/7WwQbPuESC.