【发布时间】:2021-11-01 09:45:42
【问题描述】:
我正在尝试编写一个 Go 程序来解析 ans.1 BER 二进制补码整数编码。但是,整数可以有 1、2、3 或 4 字节长度编码(取决于它的大小)。
根据规范 (http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf),最左边的位始终是补码。
什么是干净的方法?
func ParseInt(b []byte) (int64, error) {
switch len(b) {
case 1:
// this works
return int64(b[0]&0x7f) - int64(b[0]&0x80), nil
case 2:
// left most byte of b[0] is -32768
case 3:
// left most byte of b[0] is -8388608
case 4:
// left most byte of b[0] is -2147483648 (and so on for 5, 6, 7, 8)
case 5:
case 6:
case 7:
case 8:
default:
return 0, errors.New("value does not fit in a int64")
}
}
ParseInt([]byte{0xfe}) // should return (-2, nil)
ParseInt([]byte{0xfe, 0xff}) // should return (-257, nil)
ParseInt([]byte{0x01, 0x00}) // should return (256, nil)
【问题讨论】:
-
如果您从规范中引用准确的解析规则,那将是一个很大的帮助。理想情况下,将
// how do I handle this?替换为// get the lower byte, ...。