VB.Net - How to convert decimal number to HEX or Binary?

predseda

Newcomer
Joined
Jan 2, 2004
Messages
21
Location
Slovakia - European Union
255(dec) = FF(hex) = 11111111(BIN)

I have a decimal number (Dim i As Byte / Integer) an i need to convert it to string and transform it to hex or binary.
I know how to do this manually, but i think in .NET are implemented instructions for tihs.

Example:
Dim i As Byte = 255
Dim str As String

str = i.ConvertToHEX ' How to do this?
Console.WriteLine str

----
Output : FF

Thanx

predseda
 
Thanks a lot PlausiblyDamp,

s = i.ToString("X")
So this is hexadecimal number system, what about Binary?
---
And next situation, convert string with hex/binary value to integer variabile
Dim str As String = "FF"
Dim int As Integer

int = Convert_To_Integer_From_HEX(str)

Thanks

predseda
 
To convert from/to arbitrary bases, use Convert:
C#:
int i = 33;
string binary = Convert.ToString(i, 2);
string hex = Convert.ToString(i, 16);
int binaryToInt = Convert.ToInt32(binary, 2);
int hexToInt = Convert.ToInt32(hex, 16);

Though I prefer the ToString method to convert an int to hex, when needed. I would guess that internally, the ToString method for an int is using Convert.ToString behind the scenes so it might be a bit faster. I'd go with whatever seems easier to read/understand for you.

-ner
 
An easier way to do convert to hex would be to use the Conversion.Hex() function:
C#:
Code:
int i = 65;
string hex = Conversion.Hex(i);

VB:
Code:
Dim i As Integer = 65
Dim hex As String = Conversion.Hex(i)
 
Back
Top