Jump to content

BinaryWriter negative numbers?

- - - - -

  • Please log in to reply
8 replies to this topic

#1
TCristoforo

TCristoforo

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
Hi guys,

I'm trying to read a list of negative numbers(ie: -200) and use .NET's BinaryWriter to write the number as a 16-bit integer, unfortunately I'm not having much luck.

Has anyone else had luck with using the binarywriter to output negative numbers?

#2
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 242 posts
I'm not sure what kind of problem you are having. Is the input list text? Are you converting them to Int16?

#3
TCristoforo

TCristoforo

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
Yes, what I'm doing is taking the number from a listbox, and of course parsing it into numeric form, then using the BinaryWriter.Write function. I'm just not sure what I'm doing wrong.

#4
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 242 posts
Post some code as it should work. You also don't explain what is going wrong :)

#5
TCristoforo

TCristoforo

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts

 if(int.parse(output) > 0)

     b.Write(UInt16.parse(output));

 else

      b.Write(Int16.parse(output));


This is the main offending code. Everytime it outputs it prints C0FF to the file, but that's no -64 in hex, which is what my test data was.

b is the BinaryWriter.

#6
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 242 posts
0xFFC0 is the twos compliment of 64 (or -64 if you like). The number is being stored with the least significant word first (like little endian, but 16 bits instead of the normal 8). In other words, that is -64.

#7
TCristoforo

TCristoforo

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
Yes, yes it is. My problem was that I was looking at it in 64 bits via Windows 7 'programmer' calculator and not as a short.

#8
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 242 posts
Now I'm really confused. You are writing to the file a short and it's stored as a short. What does windows 7 programmer calculator have to do with it?

#9
TCristoforo

TCristoforo

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
Windows 7 by default shows 64 bits, it was showing me a different number when I plugged in -64 and switched between hex and decimal, I might've just just hit the wrong button though.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users