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

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

byte to int with twos complement

问题

以下是要翻译的内容:

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

for (i=0; i<(int)len; i++) {
    s->buf16[i] = (int16_t)buf[i] - 127; 
}    
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)

for (i=0; i&lt;(int)len; i++) {
    s-&gt;buf16[i] = (int16_t)buf[i] - 127; 
}    
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

例如,

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\n",
		buf[0], buf[1], uint16(buf16[0]), uint16(buf16[1]),
	)
}

输出:

buf 7c 82, buf16 fffd 3
英文:

For example,

package main

import (
	&quot;fmt&quot;
)

func main() {

	buf := []byte{0x7c, 0x82}
	buf16 := make([]int16, len(buf))
	for i := range buf {
		buf16[i] = int16(buf[i]) - 127
	}
	fmt.Printf(
		&quot;buf %x %x, buf16 %x %x\n&quot;,
		buf[0], buf[1], uint16(buf16[0]), uint16(buf16[1]),
	)
}

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:

确定