none
Little Endian To Short Returning Negative?

    Question

  • Hey guys, so I have been working on a Opcode reader for a C# program of mine. It works great, but all the bytes are in little endian so it gets a little annoying at times. Well I ran into a slight problem tonight.

    Lets take these little endian bytes:

    00 B8

    The original was:

    B8 00

    After using this C# code

    return (short)((ReadByte()) | (ReadByte() << 8));

    Which is pretty self explanatory, I get FFFFB800 which is close but its negative!

    I don't want to use any BitConverter classes or anything, just hands on math because I will

    be porting this code later. Anyways, what am I doing wrong here? I can't seem to figure it out. Thanks guys

    Yours truly,

    Matt

    Saturday, November 09, 2013 9:42 AM

Answers

  • short is a signed integer. Wich means the first bit is used for the sign.

    UShort is his unsigned cousin.

    See here for reference:

    http://msdn.microsoft.com/en-us/library/47zceaw7.aspx


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.

    Saturday, November 09, 2013 11:30 AM
  • Use ushort instead of short.  Remember a short is 16 bits so you have to pass the function two bytes at a time.

    jdweng

    Saturday, November 09, 2013 1:26 PM
  • Alternatively use Byte: 8 Bit, unsigned integer.


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.

    Saturday, November 09, 2013 5:22 PM

All replies

  • short is a signed integer. Wich means the first bit is used for the sign.

    UShort is his unsigned cousin.

    See here for reference:

    http://msdn.microsoft.com/en-us/library/47zceaw7.aspx


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.

    Saturday, November 09, 2013 11:30 AM
  • Use ushort instead of short.  Remember a short is 16 bits so you have to pass the function two bytes at a time.

    jdweng

    Saturday, November 09, 2013 1:26 PM
  • Alternatively use Byte: 8 Bit, unsigned integer.


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.

    Saturday, November 09, 2013 5:22 PM