I have a string that contains the next value: 0x6007.(stringToShort)
I want to convert this string to short var, however, when I attempt to convert it the next way:
short s = ((short)Convert.ToUInt16(stringToShort, 16));
then s equals to 24583
and not to 0x6007
as I need.
Can anyone help?
Values like "0x6007" and "24583" are for human consumption. They are textual representations of a number, and are meaningful only for humans.
As far as the computer is concerned, when dealing with actual numbers, it only understands binary (and even there, only in an abstract sense…it doesn't literally store the binary digits 0s and 1s).
Any time you ask the computer what number it's thinking of, it will convert from that binary-based representation to a human-readable representation (even if binary…we puny humans can't see the state of the bits in the computer and have to ask the computer to translate them to a visual representation).
When you store the value 0x6007
in (for example) a short
variable, that variable contains the value 0x6007
. It also contains the value 24583
. Oh, and it also contains the value 110000000000111
(binary), and the value 60007
(octal), and even the value 12287
(base twelve). Because what the computer is storing is not any of those specific representations of numbers, but rather its own internal representation of the magnitude any of those human-readable numbers represent.
But they are all the same. And when you parse a human-readable string like "0x6007", you do get exactly that value in the variable into which you stored the result, i.e. the computer's internal representation of a number having the same magnitude.
By default, if you ask the computer to tell you what that value is, it will give you the decimal representation of "24583". But if you want the hexadecimal representation, you need only ask nicely and the computer will give that to you instead (e.g. switch the numeric display format in your debugger, or use the "X" numeric format specifier in string.Format()
, Console.WriteLine()
, etc.).