简体   繁体   English

将byte []转换为short []

[英]Convert byte[] to short[]

Okay, I'm trying to convert a byte[] to a short[], or Int16[]. 好的,我正在尝试将byte []转换为short []或Int16 []。

List<Int16[]> lol = new List<Int16[]>();
byte[] b = System.Text.Encoding.Default.GetBytes("lolololololololololololoolol");
lol.Add(Convert.ToInt16(b));

MessageBox.Show(Encoding.Default.GetString(Encoding.Default.GetBytes(lol[0])));

That is something that I tried, but obviously, it doesn't work. 这是我尝试过的方法,但显然不起作用。 So how would I do this? 那我该怎么做呢?

It looks to me like you want to convert an entire array in one line. 在我看来,您想要在一行中转换整个数组。 It could be done like this: 可以这样完成:

List<Int16[]> lol = new List<Int16[]>();
byte[] b = System.Text.Encoding.Default.GetBytes("lolololololololololololoolol");
lol.Add(Array.ConvertAll(b, x => Convert.ToInt16(x)));

You have to go through the byte array, and convert each element. 您必须遍历字节数组,并转换每个元素。

List<Int16[]> lol=new List<Int16[]>();
byte [] b=System.Text.Encoding.Default.GetBytes("lolololololololololololoolol");
Int16 [] a=new Int16 [b.Length];
for (Int32 i=0;i<a.Length;++i) {

    a[i]=Convert.ToInt16(b[i]);

}
lol.Add(a);

You probably want BitConverter.ToInt16() , which you'd need to call for each pair of bytes. 您可能需要BitConverter.ToInt16() ,您需要为每个字节对调用它。

Or, use Buffer.BlockCopy to do it all at once (using the machine's native byte order). 或者,使用Buffer.BlockCopy一次完成所有操作(使用计算机的本机字节顺序)。

        byte[] by = new byte[5];
        short[] sh = new short[5];
        by[0] = 0x1;
        by[1] = 0x2;
        by[2] = 0x3;
        by[3] = 0x4;
        by[4] = 0x5;

        for (int x = 0; x < sh.GetLength(0); x++)
        {
            sh[x] = by[x];
            MessageBox.Show(by[x].ToString());

That worked for me. 那对我有用。 Not sure if I am misunderstanding or not. 不知道我是否误会了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM