Data Conversion (binary, hex, dec., etc.)

G

Guest

Hi,

Are there any built-in methods in VB.NET that convert one number in one
format to its equivalent in another format?

For example I want to convert the number 162 (decimal) to 10100010 (binary)
or to A2 (hexadecimal) and vice versa.

Thanks.
 
H

Herfried K. Wagner [MVP]

Amjad said:
Are there any built-in methods in VB.NET that convert one number in one
format to its equivalent in another format?

For example I want to convert the number 162 (decimal) to 10100010
(binary)
or to A2 (hexadecimal) and vice versa.

VB provides the functions 'Hex' and 'Oct'. You can use 'CLng' to parse a
string containing a number in dexadecimal or octal format:

\\\
Dim s As String = Hex(222)
MsgBox(s)
Dim i As Integer = CInt("&H" & s)
MsgBox(CStr(i))
///

The same using the .NET FCL:

\\\
Dim s As String = Convert.ToString(222, 16)
MsgBox(s)
Dim i As Integer = Convert.ToInt32(s, 16)
MsgBox(CStr(i))
///
 
G

Guest

Thanks.

Is there any built-in methods that convert decimal to BINARY?
Or do I have to write this conversion function myself?

Amjad
 
J

Jay B. Harlow [MVP - Outlook]

Amjad,
As Herfried stated, you can use the Convert class to do this.

An integer is always stored as an Integer. When you are talking decimal &
binary you are "really" talking about string representations of those
numbers

The second parameter to Convert.ToString & Convert.ToInt32 is the base you
desire.

So to convert an Integer to Binary you would use Convert.ToString(222, 2),
to convert the same integer to Decimal you can use Convert.ToString(222,
10). Of course Decimal is the normal string reprentation of numbers so you
can just as easily use Convert.ToString(222) or 222.ToString().

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top