英文:
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*
),len
是buf
的长度。
我想将其移植到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<(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]);
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 (
"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]),
)
}
Output:
<pre>
buf 7c 82, buf16 fffd 3
</pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论