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();                                 

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?

  • 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
    Mar 13 '19 at 4:50

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)

  • \$\begingroup\$ Good catch. But maybe you could also explain how to correctly parse a hexadecimal-encoded file into integer values? \$\endgroup\$
    – Philipp
    Mar 12 '19 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
    Mar 12 '19 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.