Why is the binary number flipped when reading from a byte array?
-
I am reading UDP packets that a router is sending to me. In this example i am reading the "system uptime" field which starts at bit position 64 from the begining of the packet and is a 32 bit field. So the end of the field is calculated to end at 95. I know that the first byte of this two bit field prints to the console 69 when i Console.WriteLine(buffer[8]). When I do a Convert.ToString(buffer[8],2) I get 101000101 printed on the console. I converted this byte to a decimal number. unfortunatly this is revered! and is being counted LEFT to RIGHT! When the binary numbers should start from Right to left. the real binary number of 69 is 01000101. which is the mirror opposite of what the console printed. Do you have any idea why this is? Here is the code that I am looking at. public static uint Parse(byte[] datagram, int offset, int length) { uint total = 0; int byte_index; int bit_offset; int bit; byte b; for ( int i = 0; i < length; i++ ) { bit_offset = (offset+i) % 8; byte_index = (offset+i-bit_offset) / 8; b = datagram[byte_index]; //Writing the datagram to the console and performing the Convert.ToString is where i notice this. bit = (int)(b >> (7 - bit_offset)); bit = bit & 0x0001; if ( bit > 0 ) { total += (uint)Math.Pow(2,length-i-1); } } return total; } Is this why there is the shift right and then the AND to somehow fix this issue?
-
I am reading UDP packets that a router is sending to me. In this example i am reading the "system uptime" field which starts at bit position 64 from the begining of the packet and is a 32 bit field. So the end of the field is calculated to end at 95. I know that the first byte of this two bit field prints to the console 69 when i Console.WriteLine(buffer[8]). When I do a Convert.ToString(buffer[8],2) I get 101000101 printed on the console. I converted this byte to a decimal number. unfortunatly this is revered! and is being counted LEFT to RIGHT! When the binary numbers should start from Right to left. the real binary number of 69 is 01000101. which is the mirror opposite of what the console printed. Do you have any idea why this is? Here is the code that I am looking at. public static uint Parse(byte[] datagram, int offset, int length) { uint total = 0; int byte_index; int bit_offset; int bit; byte b; for ( int i = 0; i < length; i++ ) { bit_offset = (offset+i) % 8; byte_index = (offset+i-bit_offset) / 8; b = datagram[byte_index]; //Writing the datagram to the console and performing the Convert.ToString is where i notice this. bit = (int)(b >> (7 - bit_offset)); bit = bit & 0x0001; if ( bit > 0 ) { total += (uint)Math.Pow(2,length-i-1); } } return total; } Is this why there is the shift right and then the AND to somehow fix this issue?
See endianness for information and see IPAddress.NetworkToHostOrder() for conversion methods.