By StackingofOverflows

2019-03-12 04:19:12 8 Comments

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?


@JeffUK 2019-03-12 10:43:04

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)

@Philipp 2019-03-12 10:51:46

Good catch. But maybe you could also explain how to correctly parse a hexadecimal-encoded file into integer values?

@JeffUK 2019-03-12 10:53:03

@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.

Related Questions

Sponsored Content

2 Answered Questions

2 Answered Questions

[SOLVED] Unity Transform.Position not returning expected position

1 Answered Questions

[SOLVED] How can I read an image from a binary file?

2 Answered Questions

[SOLVED] Texture2D.SetPixel method behaving weirdly in game province creation

  • 2017-02-02 18:24:13
  • the_OTHER_DJMethaneMan
  • 213 View
  • 0 Score
  • 2 Answer
  • Tags:   c# unity textures

2 Answered Questions

1 Answered Questions

[SOLVED] Unable to save player data in a binary file within Update() method

  • 2016-07-07 13:58:26
  • RationeUtor
  • 105 View
  • 2 Score
  • 1 Answer
  • Tags:   unity binary

1 Answered Questions

[SOLVED] How to read a custom binary file made with Adobe air into Unity 3D & C#

  • 2016-01-20 02:28:32
  • M. Bedi
  • 378 View
  • 0 Score
  • 1 Answer
  • Tags:   file compression

0 Answered Questions

HLSL - Binary operations

1 Answered Questions

[SOLVED] Unity3d reading profiler binary information

  • 2013-09-20 19:00:14
  • Timothy Williams
  • 1047 View
  • 2 Score
  • 1 Answer
  • Tags:   c# unity file

1 Answered Questions

[SOLVED] 3d objects in binary files

Sponsored Content