Convert hexa

  • Thread starter Thread starter [Gho]
  • Start date Start date
G

[Gho]

How to convert a Hexa value to negative and non negative
value :
if i get 0x1d = result should be 29
but if i get fd = result should be -3

How to do that
 
Gho,

I don't think that is right. Why can't fd equal 253? It all depends on
the type that you are trying to convert to. Based on that, if the initial
bit is set, then it is a negative number, otherwise, it is a positive one.
However, even converting to an signed byte, a value of fd should come out
to -115 (I believe). I think that a value of 8d will give you -3 though.

Regardless, to convert from a string representation to a value, you can
use the Parse method on the Int32 (or other numeric types, Int16, Byte, etc,
etc) to convert from a string to a value. Use the overload that takes a
NumberStyles enumeration value and pass NumberStyles.HexNumber for that
parameter.

Hope this helps.
 
Nicholas Paldino said:
I don't think that is right. Why can't fd equal 253? It all depends on
the type that you are trying to convert to. Based on that, if the initial
bit is set, then it is a negative number, otherwise, it is a positive one.
However, even converting to an signed byte, a value of fd should come out
to -115 (I believe). I think that a value of 8d will give you -3 though.

I don't think so - bear in mind that 0xff (all bits set) should be the
bit pattern for -1.
Regardless, to convert from a string representation to a value, you can
use the Parse method on the Int32 (or other numeric types, Int16, Byte, etc,
etc) to convert from a string to a value. Use the overload that takes a
NumberStyles enumeration value and pass NumberStyles.HexNumber for that
parameter.

Or in this case, just cast from the byte to sbyte - I think that would
work better, as I suspect that SByte.Parse will assume the range of the
type is the range of the string to accept (as it were) with no overflow
- and overflow is basically what the OP wants, I think.
 
Back
Top