简体   繁体   English

我如何将字节转换为短裤

[英]c# - How can i convert bytes to shorts

I am trying to convert a byte array to a array to shorts but it doesn't seem to work. 我正在尝试将字节数组转换为短裤数组,但它似乎不起作用。 The issue is, my for loop will stop when it gets to the bitconverter. 问题是,我的for循环在到达bitconverter时将停止。 Here is my code snippet: 这是我的代码段:

byte[] input = File.ReadAllBytes("frame.jpg");
short[] output = new short[input.Length / 2];
Console.WriteLine("Converting bytes to shorts");
for (int i = 0; i == input.Length; i++)
{
    output[i/2] = BitConverter.ToInt16(input, i);
    Console.WriteLine(Convert.ToString(output[i/2]) + " ");
}

I appreciate any help you can give. 感谢您提供的任何帮助。

Yesterday I posted a hasty answer and deleted it, because well in all honesty the question could be a lot better... With some deduction I have come to the conclusion that what you actually want to do is load a bunch of bytes into their word representation. 昨天我发布了一个仓促的答案并删除了它,因为老实说,这个问题可能会好得多...经过一些推论,我得出的结论是,您真正想要做的就是在他们的单词中加载一堆字节表示。 Meaning shift the first byte left by 8 bits and add the second byte. 含义是将第一个字节左移8位,然后加上第二个字​​节。

byte[] bytes = File.ReadAllBytes("frame.jpg");
var output = new List<ushort>();
for (int i = 0; i < bytes.Length; i += 2)
{
    try
    {
        output.Add((ushort)((bytes[i] * 256) + bytes[i + 1]));
    }
    catch (IndexOutOfRangeException ex)
    {
        output.Add((ushort)(bytes[i] * 256));
    }
}
return output.ToArray();

It wasn't far off, just a few logic errors in the for loop: 离那儿不远,在for循环中只有几个逻辑错误:

public static void Main()
{
        byte[] input = File.ReadAllBytes("frame.jpg");
        short[] output = new short[input.Length / 2];
        Console.WriteLine("Converting bytes to shorts");
        for (int i = 0; i < input.Length-1; i+=2)
        {
            output[i/2] = BitConverter.ToInt16(input, i);
            Console.WriteLine(Convert.ToString(output[i/2]) + " ");
        }   
}

You should also probably check that the input image has an even number of bytes. 您可能还应该检查输入图像的字节数是否为偶数。

You used ToInt16(input, i) in your code. 您在代码中使用了ToInt16(input, i) So I think this was wrong. 所以我认为这是错误的。 I suggest you to use BitConverter.ToInt16(new byte[2] {(byte)input[i] , (byte)input[i+1] },i) to fix your issues. 我建议您使用BitConverter.ToInt16(new byte[2] {(byte)input[i] , (byte)input[i+1] },i)来解决您的问题。

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

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