我正在嘗試編寫Go程序來解析ans.1 BER二進制補碼整數編碼。但是,整數可以具有1,2,3或4字節長度編碼(取決於其大小)。int64的可變長度二進制補碼
根據規範(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)
這將是一個很大的幫助,如果你引述確切規則從規範分析。理想情況下,用'//如何處理這個?'替換'//得到低位字節,...'。 –