Number System Functions
Function |
Description |
Hex(x) |
Returns a string representing the hexadecimal equivalent of x (i.e., it converts a decimal number to a hexadecimal number).
Example:
Print "The decimal number 687 is "; Hex(687); " in hex."
The output of the line above would be:
The decimal number 687 is 2AF in hex.
|
Oct(x) |
Returns a string representing the octal equivalent of x (i.e., it converts a decimal number to a octal number).
Example:
Print "The decimal number 627 is "; Oct(627); " in octal."
The output of the line above would be:
The decimal number 627 is 1163 in octal.
|
&H before a number means that the number is specified in hex:
Example:
Const intHexNum As Integer = &H2AFS
Console.WriteLine(CStr(intHexNum))
Output:
687
&O before a number means that the number is specified in octal:
Example:
Const intOctNum As Integer = &O1163
Console.WriteLine(CStr(intOctNum))
Output:
627
Converting a Hex or Octal Number to Decimal
To convert a hexadecimal or octal number to a decimal value, you must treat the hex or octal value as a string, append "&H" or "&O" in front of the value, and use a conversion function such as Val or CInt to convert the string to a numeric value.
To illustrates the concepts presented above, create a new "Try It" project, and place the following code in Sub Main:
Const intDECIMAL_NUMBER_1 As Integer = 687
Const intDECIMAL_NUMBER_2 As Integer = 627
Const intHEXADECIMAL_NUMBER As Integer = &H2AFS
Const intOCTAL_NUMBER As Integer = &O1163S
Const strHEX_STRING As String = "BEEF"
Const strOCT_STRING As String = "411"
Dim strHexVal As String
Dim strOctVal As String
Dim intDecVal As Integer
strHexVal = Hex(intDECIMAL_NUMBER_1)
Console.WriteLine("The decimal number " & CStr(intDECIMAL_NUMBER_1) & " is " & strHexVal & " in hex.")
strOctVal = Oct(intDECIMAL_NUMBER_2)
Console.WriteLine("The decimal number " & CStr(intDECIMAL_NUMBER_2) & " is " & strOctVal & " in octal.")
Console.WriteLine("The Integer Constant specified as '&H2AF' evaluates to: " & CStr(intHEXADECIMAL_NUMBER))
Console.WriteLine("The Integer Constant specified as '&O1163' evaluates to: " & CStr(intOCTAL_NUMBER))
intDecVal = CInt("&H" & strHEX_STRING)
Console.WriteLine(strHEX_STRING & " in hex is equivalent to " & CStr(intDecVal) & " in decimal.")
intDecVal = CInt("&O" & strOCT_STRING)
Console.WriteLine(strOCT_STRING & " in octal is equivalent to " & CStr(intDecVal) & " in decimal.")
Console.ReadLine()
Run the project. The output is shown in the screen shot on the right: |
Download the VB project code for the example above here.
If you wish to review number systems theory, a comprehensive tutorial in PDF format is available via the "Number Systems Tutorial" link below. This tutorial covers the binary, hexadecimal, and octal number systems – including how to convert from one number system to the other and how to perform addition and subtraction in these systems.