Understanding Numeric Data in VBScript - Conversion Functions
(Page 4 of 5 )
Let’s begin by examining the conversion functions that VBScript provides for converting actual numbers between the different number systems. VBScript provides functions for converting numbers (assumed to be in decimal notation) into either Hex or Octal.
Hex(number)
Oct(number)
The Hex function returns a string representing the hexadecimal value of a given number. The number provided may be any valid expression.
MyHex = Hex(5) ' Returns 5.
MyHex = Hex(10) ' Returns A.
MyHex = Hex(459) ' Returns 1CB.
If the number provided is not a valid integer, it will be rounded to the nearest whole number before being converted.
If the expression provided does not evaluate to a Boolean (or some other value) its numeric representation will be used in the conversion.
The Oct function returns a string representing the octal value of a given number. The number argument, again, may be any valid expression.
MyOct = Oct(4) ' Returns 4.
MyOct = Oct(8) ' Returns 10.
MyOct = Oct(459) ' Returns 713.
There are no functions for converting to decimal as this is done automatically for any expression that does not use one of the above functions. Take the following code for example.
MyHex = &h14
MyOct = &o101
WScript.Echo "0x14 = " & MyHex
WScript.Echo "O101 = " & MyOct
You can use special notations to indicate that numbers are in a different base. To distinguish hexadecimal numbers, prepend the number with a “0x”. For octal numbers, simply add a leading 0. Any normal integers are assumed to be in decimal notation.
In VBScript you can use special notations to indicate numbers are of a different base as well. Prepending with a “&h” indicates a hexadecimal number while a “&o” indicates an octal number.
So you can see in our code example that we’ve supplied both a hexadecimal and an octal number. Using them in an expression results in their decimal equivalents. The example has the following output:
0x14 = 20
O101 = 65
Unfortunately, VBScript doesn’t provide a nice way of handling binary data. It’s best to create a function that can do that for you whenever the need arises. Remember how easy we found it was to convert binary to hexadecimal earlier? You should be able to build a converter function with that knowledge.
Hint: Treat your numbers as strings using the functions you’ll find later in this article!
Next: Converting data types >>
More BrainDump Articles
More By Nilpo