Converting datetime OctetString to human readable string in GoLang

huangapple go评论113阅读模式
英文:

Converting datetime OctetString to human readable string in GoLang

问题

如何将Datetime Octetstring转换为ASCII?我阅读了python netsnmp中的一个示例,但仍然无法解决问题。

这是我从gosnmp收到的[]uint8切片:

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

或者Go语法表示的值:

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

日期时间的输出应该类似于:

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

这是mibs:oid:HOST-RESOURCES-MIB::hrSWInstalledDate

有人可以给我一些关于如何使用binary将其解码为可读的ASCII或字符串的想法吗?

英文:

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.

答案1

得分: 2

这是一个用于将 SNMP 八位字节字符串转换为人类可读日期格式的代码示例。如果你只需要创建一个符合你提到的格式的日期/时间字符串,可以使用以下代码:

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))
}

你可以在这里查看代码示例:https://play.golang.org/p/7WwQbPuESC。

英文:

The format is described here: https://stackoverflow.com/questions/4571899/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]) &lt;&lt; 8) | int(c[1])
    return fmt.Sprintf(&quot;%d-%d-%d,%02d:%02d:%02d.%d,%c%d:%d&quot;, 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.

huangapple
  • 本文由 发表于 2016年11月28日 02:36:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/40832472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定