开发者

Storing a hexadecimal value in a variable (Dim xx as "Hex") in VB.NET

How can I sto开发者_运维问答re a hexadecimal number in a variable without it becoming a decimal?

Or do I have to store it as either a string or integer?


I think you've misunderstood how numbers work.

Numbers themselves aren't hex, decimal or binary - that's just their representation, whether in code or in memory.1

What you get when you add together five and five is ten, whether you format that as 10 or &H0A.

So these statements are exactly equivalent:

 Dim x As Integer = 16
 Dim x As Integer = &H10

Both put the same value into the variable.

If you want to later format that value as hex, then you should do so - e.g. with the "x" format specifier. But the value itself isn't hex or decimal.

Dim y As Integer = &H23
Console.WriteLine(y) ' Prints 35
Console.WriteLine(y.ToString("x")) ' Prints 23

EDIT: If you really want to do this, you could always create your own structure which took an integer value in its constructor and overrode ToString to format it in hex. I'd strongly recommend that you don't do this though.


1 Admittedly the representation can significantly affect what you can do with the number and what results you'll get - as seen by the difference between Double and Decimal. We'll leave that out of the equation for the moment though.


Integers in .NET are not stored as decimal, they are stored as binary in two's complement representation. Both decimal and hexadecimal are just different ways of reoresenting the number in a more human-friendly way.

If you want to output a number as hexadecimal you can use the "x" or "X" format specifier with the ToString method (which output lower- and upper-case respectively) with an optional fixed number of characters specified as "n" where n is the number of characters.

Some examples of outputting an integer as hex:

Dim n as Integer = &HBEEF;
Console.WriteLine(n.ToString("x")) ' output in lower case, e.g. beef '
Console.WriteLine(n.ToString("X")) ' output in upper case, e.g. BEEF '
Console.WriteLine(n.ToString("X8")) ' upper case & 8 chars, e.g. 0000BEEF '


If you store a value in a variable, it will be neither in decimal nor hexadecimal form. Eventually it ends up in your computer's RAM in binary form. To the computer, the decimal number 17 and hexadecimal &H11 are identical. The difference is purely lexical and disappears once the compiler has done its work.

If you want to preserve a value's representation in hexadecimal form, you need to store it as a string.


dim myNum as Integer = &H100 '&HB

Console.WriteLine(myNum)

EDIT: You could store the expression as string & use Int.Parse or any other Parse or TryParse method, if that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜