簡體   English   中英

我如何將字節轉換為短褲

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

我正在嘗試將字節數組轉換為短褲數組,但它似乎不起作用。 問題是,我的for循環在到達bitconverter時將停止。 這是我的代碼段:

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]) + " ");
}

感謝您提供的任何幫助。

昨天我發布了一個倉促的答案並刪除了它,因為老實說,這個問題可能會好得多...經過一些推論,我得出的結論是,您真正想要做的就是在他們的單詞中加載一堆字節表示。 含義是將第一個字節左移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();

離那兒不遠,在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]) + " ");
        }   
}

您可能還應該檢查輸入圖像的字節數是否為偶數。

您在代碼中使用了ToInt16(input, i) 所以我認為這是錯誤的。 我建議您使用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