0

I am trying to convert hex data to signed int/decimal and can't figure out what I'm doing wrong.

I need FE to turn into -2.

I'm using Convert.ToInt32(fields[10], 16) but am getting 254 instead of -2.

Any assistance would be greatly appreciated.

Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • 1
    Can you explain why you want to turn `FE` into `-2` instead of `254` and how do you know that you need to get `-2` instead of `254`? – George Alexandria Sep 13 '17 at 17:26
  • The guy I'm working with wants to see a signed value, not sure why but that's what was requested. It's possible though. This link does it in JavaScript. http://www.free-test-online.com/binary/signed_converter.html – StarScr3am77 Sep 13 '17 at 17:29
  • That is not a signed int decimal - it's a signed byte if you want to read it that way. – Michael Dorgan Sep 13 '17 at 17:29

3 Answers3

4

int is 32 bits wide, so 0xFE is REALLY being interpreted as 0x000000FE for the purposes of Convert.ToInt32(string, int), which is equal to 254 in the space of int.

Since you're wanting to work with a signed byte range of values , use Convert.ToSByte(string, int) instead (byte is unsigned by default, so you need the sbyte type instead).

Convert.ToSByte("FE",16)

Tyler Lee
  • 2,736
  • 13
  • 24
2

Interpret the value as a signed byte:

sbyte value = Convert.ToSByte("FE", 16); //-2
mitaness
  • 695
  • 7
  • 13
0

Well the bounds of Int32 are -2 147 483 648 to 2 147 483 647. So FE matches 254.

In case you want to do a wrap around over 128, the most elegant solution is proably to use a signed byte (sbyte):

csharp> Convert.ToSByte("FE",16);   
-2
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555