2
\$\begingroup\$

I am trying to display the first two bytes of a binary file as a test. I have the following code.

 void DisplayValuestext(){
  Stream s = new FileStream("Assets//testbinary.bin", FileMode.Open);
  BinaryReader br = new BinaryReader(s);
  int dataVal = br.ReadUInt16();                                 
  Debug.Log(dataVal);
 }

The first 2 bytes of the binary file are "1E44" which the function ReadUInt16() should read. However, it reads the first byte of data, "1E" rather then the first 2 bytes "1E44". I believe it is because it reads 2 characters, rather than 2 bytes. When I display the 16 bit unsigned integer "dataVal" in the console, I get 25905. The value I am trying to get is 17438 which is "1E44" little-endian encoded value converted to decimal.

I have also attempted to use the function "ReadUInt32". This method should read the first 4 bytes, however it instead displaces by 4 characters, which is 2 bytes "1E44". The console displays "875849009".

Why do I get these strange values "25905" and "875849009" and how can I resolve this to get the desired value of 17438?

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Note: in case you are unaware, I fee the need to point out that the way you are reading data will not work in a built game. If you are writing editor-only code you should be fine, but if you are going to be reading this data at runtime, it’s going to need to be stored either as a text asset eg. a .bytes file, possibly in a Resources folder) or in StreamingAssets. \$\endgroup\$
    – Ed Marty
    Commented Mar 13, 2019 at 4:50

1 Answer 1

2
\$\begingroup\$

Your file is not a binary file.

It contains ASCII text, starting "1e"...

The value of which is 65 31 in Hex (Little endian encoded), Or 25905 in Decimal.

1e44(ascii)= 34 34 65 31 (hex) = 875849009 (dec)

\$\endgroup\$
2
  • \$\begingroup\$ Good catch. But maybe you could also explain how to correctly parse a hexadecimal-encoded file into integer values? \$\endgroup\$
    – Philipp
    Commented Mar 12, 2019 at 10:51
  • \$\begingroup\$ @Philipp that's very much not the question! OP might actually be getting the correct value if it really is a binary file, but just misunderstanding what output they should expect. To be honest, both are better suited to SO than here. \$\endgroup\$
    – JeffUK
    Commented Mar 12, 2019 at 10:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .