简体   繁体   English

将字符串转换为短

[英]Convert string to short

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: 我有一个包含下一个值的字符串: 0x6007.(stringToShort)我想将此字符串转换为short var,但是,当我尝试以另一种方式转换时:

short s = ((short)Convert.ToUInt16(stringToShort, 16));

then s equals to 24583 and not to 0x6007 as I need. 然后s等于24583而不是我需要的0x6007

Can anyone help? 有人可以帮忙吗?

Values like "0x6007" and "24583" are for human consumption. 诸如“ 0x6007”和“ 24583”之类的值供人类使用 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). 就计算机而言,在处理实际数字时,它仅理解二进制(甚至在那里,仅是抽象意义上的……它实际上不存储二进制数字0和1)。

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 . 当将值0x6007存储在(例如) short变量中时,该变量包含值0x6007 It also contains the value 24583 . 它还包含值24583 Oh, and it also contains the value 110000000000111 (binary), and the value 60007 (octal), and even the value 12287 (base twelve). 哦,它也包含了价值110000000000111 (二进制),和值60007 (八进制),甚至是价值12287 (基地十二)个。 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, ie the computer's internal representation of a number having the same magnitude. 而且,当您解析人类可读的字符串(例如“ 0x6007”)时,您确实会在存储结果的变量中得到该值,即计算机内部表示的幅度相同的数字。

By default, if you ask the computer to tell you what that value is, it will give you the decimal representation of "24583". 默认情况下,如果您要求计算机告诉您该值是多少,它将以十进制表示形式“ 24583”。 But if you want the hexadecimal representation, you need only ask nicely and the computer will give that to you instead (eg switch the numeric display format in your debugger, or use the "X" numeric format specifier in string.Format() , Console.WriteLine() , etc.). 但是,如果您要使用十六进制表示形式,则只需要很好地询问即可,计算机会自动将其提供给您(例如,在调试器中切换数字显示格式,或在string.Format()使用“ X”数字格式说明符, Console.WriteLine()等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM