3

Given a byte in two's complement form, I am attempting to convert that byte into it's decimal representation. For example the byte 10000000 I would need to convert to -128 and the byte 01111111 I would need to convert to 127. I've looked at this answer, but I haven't been successful with taking one of the answers and making it work for me.

How do I go about doing the conversion?

CLARIFICATION: I'm trying to convert a byte in two's complement form into an int and not a string representation of a binary value into an `int.

  • Possible duplicate of [Convert binary string into integer](https://stackoverflow.com/questions/9149728/convert-binary-string-into-integer) – oppassum Feb 01 '18 at 16:18
  • Use this: int i = BitConverter.ToInt32(bytes, 0); where bytes is your byte array :) – Dina Bogdan Feb 01 '18 at 16:19
  • 2
    int value = (sbyte)byteval; – Hans Passant Feb 01 '18 at 16:23
  • 2
    `11111111` in two's complement is not -128. Are you sure that's the correct test case? Could you add more test cases to the question? – Trevor Feb 01 '18 at 16:26
  • 3
    The OP is confused about what two's complement encoding means. -128 in two's complement is 10000000 in base 2. – Hans Passant Feb 01 '18 at 16:26
  • @HansPassant indeed. This works as you described `unchecked {((sbyte)0b01111111).Dump();}` with `10000000` – Panagiotis Kanavos Feb 01 '18 at 16:29
  • @HansPassant thanks for the help. I should clarify that I am starting with an unsigned byte in two's complement form. So -128 is represented as `10000000` and when trying to cast this to an `sbyte` the value is too large. –  Feb 01 '18 at 16:42

2 Answers2

3
public static int ConvertTwosComplementByteToInteger(byte rawValue)
{
    // If a positive value, return it
    if ((rawValue & 0x80) == 0)
    {
        return rawValue;
    }

    // Otherwise perform the 2's complement math on the value
    return (byte)(~(rawValue - 0x01)) * -1;
}
Haroon
  • 538
  • 2
  • 11
  • Sorry I downvoted before I checked this thoroughly. Although it is correct it's a bit complicated. If you edit your answer I'll be able to remove the downvote. Sorry – phuzi Feb 01 '18 at 16:39
3

You'll need to cast it to sbyte

byte b = 0b10000000;
sbyte s = (sbyte)b;

Console.WriteLine(s); // -128

You can convert this to an Int32 value and encapsulate this with

public static int ByteToInt32(byte value)
{
    return (sbyte)value;
}
phuzi
  • 12,078
  • 3
  • 26
  • 50