将字节转换为带有二进制补码的整数。

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

byte to int with twos complement

问题

以下是要翻译的内容:

下面的C代码片段来自于rtl_fm.c,它是rtlsdr项目的一部分(我添加了printf语句)

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

输出的示例行为:buf 7c 82, buf16 fffd 3

buf16是一个int16_t类型的数组,buf是一个字节数组(char*),lenbuf的长度。

我想将其移植到Go语言。这是我想出的代码:http://play.golang.org/p/zTRkjlz8Ll 但它没有产生正确的输出。

英文:

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

  1. for (i=0; i&lt;(int)len; i++) {
  2. s-&gt;buf16[i] = (int16_t)buf[i] - 127;
  3. }
  4. printf(&quot;buf %x %x, buf16 %x %x\n&quot;, buf[0],buf[1], s-&gt;buf16[0], s-&gt;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

得分: 2

例如,

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. buf := []byte{0x7c, 0x82}
  7. buf16 := make([]int16, len(buf))
  8. for i := range buf {
  9. buf16[i] = int16(buf[i]) - 127
  10. }
  11. fmt.Printf(
  12. "buf %x %x, buf16 %x %x\n",
  13. buf[0], buf[1], uint16(buf16[0]), uint16(buf16[1]),
  14. )
  15. }

输出:

  1. buf 7c 82, buf16 fffd 3
英文:

For example,

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. func main() {
  6. buf := []byte{0x7c, 0x82}
  7. buf16 := make([]int16, len(buf))
  8. for i := range buf {
  9. buf16[i] = int16(buf[i]) - 127
  10. }
  11. fmt.Printf(
  12. &quot;buf %x %x, buf16 %x %x\n&quot;,
  13. buf[0], buf[1], uint16(buf16[0]), uint16(buf16[1]),
  14. )
  15. }

Output:

<pre>
buf 7c 82, buf16 fffd 3
</pre>

huangapple
  • 本文由 发表于 2014年11月1日 15:08:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/26687000.html
匿名

发表评论

匿名网友

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

确定