dtll2016
2014-11-01 07:08
浏览 56
已采纳

字节到整数的二进制补码

The following snippet of C code is from rtl_fm.c which is part of the rtlsdr project (I've added the printf statement)

for (i=0; i<(int)len; i++) {
    s->buf16[i] = (int16_t)buf[i] - 127; 
}    
printf("buf %x %x, buf16 %x %x
", buf[0],buf[1], s->buf16[0], s->buf16[1]);

An example line of output is: buf 7c 82, buf16 fffd 3

buf16 is an array of type int16_t, buf is an array of bytes (char*), len is length of buf

I'd like to port this to Go. Here is what I've come up with: http://play.golang.org/p/zTRkjlz8Ll however it doesn't produce the correct output.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongmeng1402 2014-11-01 07:32
    已采纳

    For example,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
    
        buf := []byte{0x7c, 0x82}
        buf16 := make([]int16, len(buf))
        for i := range buf {
            buf16[i] = int16(buf[i]) - 127
        }
        fmt.Printf(
            "buf %x %x, buf16 %x %x
    ",
            buf[0], buf[1], uint16(buf16[0]), uint16(buf16[1]),
        )
    }
    

    Output:

    buf 7c 82, buf16 fffd 3
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题