Reputation: 10691
I am loading a file into a byte[]. By my understanding the byte[] should contain a specific elements of bytes (8-bit). When i print each byte, all of them are not 8-bit (i.e. they dont have the length of 8). My Code:
FileStream stream = File.OpenRead(@"C:\Image\Img.jpg");
byte[] fileByte = new byte[stream.Length];
stream.Read(fileByte, 0, fileByte.Length);
for (int i = 0; i <= fileByte.Length - 1; i++)
{
Console.WriteLine(Convert.ToString(fileByte[i], 2));
}
Output:
10001110
11101011
10001100
1000111
10011010
10010011
1001010
11000000
1001001
100100
I think my understanding is wrong here, Can you please let me know (or provide me some tutorial links) where I am missing this.
Upvotes: 3
Views: 1221
Reputation: 73594
When converting a numeric to a string, you lose any leading zeros. (Note that all of your entries start with "1".) You can use PadLeft to put them back in.
FileStream stream = File.OpenRead(@"C:\Image\Img.jpg");
byte[] fileByte = new byte[stream.Length];
stream.Read(fileByte, 0, fileByte.Length);
for (int i = 0; i <= fileByte.Length - 1; i++)
{
Console.WriteLine(Convert.ToString(fileByte[i], 2).PadLeft(8,'0'));
}
Upvotes: 13
Reputation: 13990
They all have 8 bits, but the non significant zeroes (the zeroes on the left) are not printed.
Upvotes: 4
Reputation: 4536
Are the bytes without leading zeros? You kinda chose a bad example because we do not know the decimal values you are displaying (ok maybe someone who knows the header structure for a .jpg file knows). I'm willing to bet leading zeros are not displayed in the binary equivalents.
Upvotes: 2