[英]Reading int16 from binary file in Golang
我目前正在研究Golang程序,該程序從stdin讀取16位整數。 我期望值在3到〜128之間,但是,當我打印出整數值時,它是完全隨機的,從30,000+到-30,000。
我通過執行以下操作在PHP中執行相同的操作:
<?php
$binary = fread($stream, 2);
$unpacked = unpack('s', $binary);
$int = reset($unpacked);
這可以成功工作。 我正在使用的Go代碼位於GitHub上: https : //github.com/uniquoooo/dca/blob/decoding/main.go#L502-L536
我正在使用bash管道(例如cat testfile | command
)將內容管道傳輸到程序中。
這是一些測試Golang代碼:
package main
import (
"bufio"
"fmt"
"encoding/binary"
"io"
"os"
"github.com/layeh/gopus"
)
func main() {
OpusDecoder, err := gopus.NewDecoder(48000, 2)
if err != nil {
panic(err)
}
_ = OpusDecoder
dcabuf := bufio.NewReaderSize(os.Stdin, 16384)
var opuslen uint16
for {
err = binary.Read(dcabuf, binary.LittleEndian, &opuslen)
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
return
}
panic(err)
}
fmt.Println("Frame Size:", opuslen)
opus := make([]byte, opuslen)
err = binary.Read(dcabuf, binary.LittleEndian, &opus)
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
return
}
panic(err)
}
// pcm, err := OpusDecoder.Decode(opus, 1920, false)
// if err != nil {
// panic(err)
// }
// err = binary.Write(os.Stdout, binary.LittleEndian, &pcm)
// if err != nil {
// if err == io.EOF || err == io.ErrUnexpectedEOF {
// return
// }
// panic(err)
// }
}
}
我希望輸出類似於Frame Size: 128
但該值要高得多。
我已經在以下位置的Google雲端硬盤上上傳了測試文件: https : //drive.google.com/file/d/0B_559nfSNrcfMUNhbWdJMGptZGs/view?usp=sharing
要運行該程序,請使用go build
build對其進行go build
,然后按以下方式運行:
cat test.dca | ./main
可執行文件名稱可能不同。
聽起來您正在獲取編碼的字節。 換句話說,1變成49,依此類推(取決於編碼)。 解決此問題的方法是將int16中每個字節的字節標准化回代表的值(例如,字節“ 0”)。
一種可能的方法是
a := uint16(((opuslen & 0xff00) >> 8) - '0')
b := uint16((opuslen & 0x00ff) - '0')
opuslen = (function to splice together)
盡管這很麻煩,但這是您必須執行的操作,以確保字節不保持其編碼。 那,或者只是不存儲為utf / ascii /任何編碼值。 對人類來說,看起來很時髦,但是在乎的是:)
您還會注意到,為了便於演示,我將opuslen更改為uint。 如果您期望負長度(可能表示壓縮?),則根據需要進行調整。
編輯:如果您確實要使用編碼的字節,也許您應該讀入字符串並使用strconv.Atoi,這將使您更輕松,因為您不必自己編寫代碼即可進行轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.