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. 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.
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:
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.