R将2个字节的原始数据转换为整数

时间:2016-06-06 21:50:13

标签: r type-conversion bitwise-operators

我有一个原始(音频)数据文件,我需要将其作为带符号的2字节整数读入R程序。下面的C代码在将文件读入unsigned char数组后成功完成转换。

我在R遇到困难,可能是因为 2个字节的异常整数大小。在C代码下面,我在此处写了我在R中的内容,以及错误消息。

#define BYTES_PER_SAMPLE 2

void samples2floats(unsigned char *audio, float *buff, int n) {
    int i;
    for (i=0; i < n; i++)  buff[i] = sample2float(audio + i*BYTES_PER_SAMPLE);
}

float sample2float(unsigned char *temp) {
    int i,tot,j,g;
    unsigned char b[BYTES_PER_SAMPLE],*ptr;
    float x;

    tot= 0;
    ptr = (unsigned char *) &tot;
    for (j = 0; j < BYTES_PER_SAMPLE; j++)  ptr[j] = temp[j];
    if (tot & 0x8000) tot |= 0xffff0000;
    x = tot / (float) 0x10000;
 }
    return(x);
}

R代码:

#read in data
maxaudio = 100000
to.read = file("filename.raw", "rb")
audio = readBin(to.read, "raw", size = 1, n = maxaudio, signed = FALSE) 
close(to.read)

audio[493:500] #what the data looks like
#[1] e9 ff eb ff ef ff ec ff

audio = sapply(audio,function(x) paste(as.integer(rev(rawToBits(x))),collapse=""))

audio[493:500] #what the data looks like
#[1] "11101001" "11111111" "11101011" "11111111" "11101111" "11111111" "11101100" "11111111"

BinToDec <- function(x)  #convert binary to decimal
  sum(2^(which(rev(unlist(strsplit(as.character(x), "")) == 1))-1))

sample2num = function(char.audio) {
  wave = numeric(0)
  for (i in 1:length(char.audio)) {
    p = (i-1)*2 + 1
    #concatenates two values, e.g. "1110100111111111", converts to int
    int.val = BinToDec(paste(toString(audio[p]), toString(audio[p+1]), sep = "")) 
    if (bitwAnd(int.val, 0x8000)) int.val = bitwOr(int.val, 0xffff) 
    #had to change 0xffff0000 to 0xffff, or got error Warning message: In    
    #bitwOr(int.val, 4294901760) : NAs introduced by coercion to integer range
    x = int.val/0x8000
    if (abs(x) > 1) stop(paste("value outside range", temp[1], temp[2], x))
    wave = c(wave, x)
  }
  return(wave)
}
test = sample2num(audio[5000:50000])

#Error in sample2num(audio[5000:50000]) : 
#  value outside range 1111111111101001 NA 1.99996948242188

1 个答案:

答案 0 :(得分:0)

更新:读取R中的数据变得如此简单:

audiodata = readBin(name, integer(), 2988032, size = 2)