字节数组转换为int16

时间:2015-03-06 01:26:15

标签: f# bytearray seq

如何获取字节数组并将其转换为多维整数数组。实际数据实际上是使用ReadBytes的System.IO.BinaryReader的结果。该函数将获取字节数组并输出新数组。

例如,给定数据将具有4xN数组中的前4个元素 256,328,344,546

以下转换适用于一对字节

let value = int bytedata.[1] ||| (int bytedata.[0] <<< 8)

我可以通过循环来实现,但似乎F#应该使这更容易。

let realdata =  [|1uy; 0uy; 1uy; 48uy; 0uy; 158uy; 0uy; 222uy; 0uy; 250uy; 0uy; 0uy; 0uy;
151uy; 2uy; 238uy; 3uy; 31uy; 1uy; 191uy; 1uy; 228uy; 1uy; 62uy; 1uy;
111uy; 0uy; 247uy; 1uy; 183uy; 0uy; 83uy; 0uy; 213uy; 2uy; 197uy; 2uy;
161uy; 1uy; 7uy; 0uy; 201uy; 1uy; 48uy; 0uy; 166uy; 0uy; 133uy; 1uy; 40uy;
0uy; 150uy; 0uy; 193uy; 2uy; 207uy; 2uy; 217uy; 1uy; 158uy; 1uy; 53uy; 1uy;
38uy; 0uy; 141uy; 0uy; 162uy; 1uy; 23uy; 0uy; 0uy; 0uy; 128uy; 2uy; 223uy;
2uy; 204uy; 1uy; 236uy; 2uy; 20uy; 1uy; 56uy; 0uy; 221uy; 0uy; 235uy; 1uy;
118uy; 0uy; 29uy; 0uy; 173uy; 2uy; 58uy; 2uy; 27uy; 1uy; 56uy;|]

let convertBytes (data : byte[]) =
seq { 
    let i = ref 0
    while !i < 10 do
        if !i%2 = 0 then 
            yield int(data.[!i] ||| (data.[!i+1] <<< 8))
        i := !i + 2
}

但是,我正在产生一个字节数组而不是一个int16数组。

1 个答案:

答案 0 :(得分:2)

首先,我假设您需要一个单维数组,至少在您的示例代码中是您想要的。

其次,你的转换数学对我来说似乎不对,如果你取[1uy; 48uy]而你的结果是49,那么[0uy; 49uy]的结果是什么?看起来你正在添加而不是转换。

如果我错了,请纠正我,但我认为这就是你所需要的:

open System
let result = 
    [|0..2..Array.length realdata-1|] 
    |> Array.map (fun i -> BitConverter.ToInt16(realdata, i))

// val r : int16 [] = [|1s; 12289s; -25088s; -8704s; -1536s; 0s; ...

或者,如果数据是Big Endian:

let result = 
    [|0..2..Array.length realdata-1|] 
    |> Array.map (fun i -> (int16 (realdata.[i]) <<< 8) ||| int16 (realdata.[i+1]))

或者你可以用你的转换替换lambda中的表达式,如果它对你有意义的话。

<强>更新

根据您的评论,您可能希望执行以下操作:

let result = 
    Array2D.init 8 (realdata.Length/16) (fun i j -> (int16 (realdata.[j * 16 + i*2]) <<< 8) ||| int16 (realdata.[j * 16 + i*2 + 1]))