IanB
IanB

Reputation: 2694

byte to int with twos complement

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.

Upvotes: 1

Views: 346

Answers (1)

peterSO
peterSO

Reputation: 166529

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:

buf 7c 82, buf16 fffd 3

Upvotes: 2

Related Questions