Reading bytes from BigEndian

  • Thread starter Thread starter TF
  • Start date Start date
T

TF

Hi,
I've a byte array with 4 elements in BigEndian format i.e. {0, 0, 0,
12} and i want to convert it to 4-byte integer (Int32). I am trying
Encoding.BigEndianUnicode property but it has no effect on the result.
It always gives me number '201326592' instead of '12'.

Any help??

Here is the code:

Dim a_byte() As Byte = New Byte() {0, 0, 0, 12}

Dim ms As New MemoryStream(a_byte)
Dim br As New BinaryReader(ms, Encoding.BigEndianUnicode)

Dim x As Int32 = br.ReadInt32() ' expecting x = 12

br.Close()
ms.Close()
 
TF said:
I've a byte array with 4 elements in BigEndian format i.e. {0, 0, 0,
12} and i want to convert it to 4-byte integer (Int32). I am trying
Encoding.BigEndianUnicode property but it has no effect on the result.
It always gives me number '201326592' instead of '12'.

The Encoding is only used when you're reading strings. You can't change
the endianness of BinaryReader/Writer, unfortunately.
 
That number is actually correct. Because it's BigEndian, then Encoding reverses your bytes into 12,0,0,0. COnverting this to binary = 00001100 00000000 00000000 00000000. If you do all the math, it comes out to 201326592. Below is a chart I made up quick in MS excel. If you add the 27th and 28th numbers (since these are set to 1 in the binary stuff above) you get 201326592. If you acutally want the number 12 to come out of your code, your byte array should look like: 12,0,0,0

1
2
4
8
16
32
64
128

256
512
1024
2048
4096
8192
16384
32768

65536
131072
262144
524288
1048576
2097152
4194304
8388608

16777216
33554432
67108864 (this one)
134217728 (and this one)
268435456
536870912
1073741824
2147483648


**********************************************************************
Sent via Fuzzy Software @ http://www.fuzzysoftware.com/
Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
 
That number is actually correct. Because it's BigEndian, then
Encoding reverses your bytes into 12,0,0,0. COnverting this to binary
= 00001100 00000000 00000000 00000000.

No, that would be little endianness. In little endianness, the least
significant byte is stored first, so 12 would be stored as {12, 0, 0,
0} - you'd reverse it to get {0, 0, 0, 12} or binary
00000000 00000000 00000000 00001100

See http://en.wikipedia.org/wiki/Endianness

The reason it's not working is because the encoding used by a
BinaryReader has nothing to do with calls to ReadInt32.
 
Back
Top