I'm getting a hex string that needs to be converted to a signed 8-bit integer. Currently I'm converting using Int16/Int32, which will obviously not give me a negative value for an 8-bit integer. If I get the value 255 in Hex, how do I convert that to -1 in decimal? I assume I want to use an sbyte, but I'm not sure how to get that value in there properly.
Asked
Active
Viewed 1.2k times
9
-
2http://msdn.microsoft.com/en-us/library/bb311038.aspx – James Black Sep 14 '10 at 00:52
-
1related and with great answers, https://stackoverflow.com/questions/4275440/how-to-convert-hex-string-to-hex-number – barlop Nov 16 '17 at 21:59
3 Answers
10
You can use Convert.ToSByte
For example:
string x = "aa";
sbyte v = Convert.ToSByte(x, 16);
// result: v = 0xAA or -86
You can also use sbyte.Parse
For example:
string y = "bb";
sbyte w = sbyte.Parse(y, System.Globalization.NumberStyles.HexNumber);
// result: w = 0xBB or -69
To answer your question about the upper or lower byte of an Int16:
string signed_short = "feff";
// Truncate 16 bit value down to 8 bit
sbyte b1 = (sbyte)Convert.ToInt16(signed_short, 16);
sbyte b2 = (sbyte)short.Parse(signed_short, System.Globalization.NumberStyles.HexNumber);
// result: b1 = 0xFF or -1
// result: b2 = 0xFF or -1
// Use upper 8 bit of 16 bit
sbyte b3 = (sbyte)(Convert.ToInt16(signed_short, 16) >> 8);
sbyte b4 = (sbyte)(short.Parse(signed_short, System.Globalization.NumberStyles.HexNumber) >> 8);
// result: b3 = 0xFE or -2
// result: b4 = 0xFE or -2

SwDevMan81
- 48,814
- 22
- 151
- 184
2
You need to perform an unchecked
cast, like this:
sbyte negativeOne = unchecked((sbyte)255);

SLaks
- 868,454
- 176
- 1,908
- 1,964
-
I guess, it is because OP was asking to convert "STRING into signed integer". Anyway, your answer was helpful to me. Thank you! :) – Anton Kedrov Dec 29 '14 at 12:36
0
My solution was to put the first take the first 8 bits of the 16 bit integer and store them in an sbyte.

alexD
- 2,368
- 2
- 32
- 43