Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hex to Decimal and Decimal to Hex?

Status
Not open for further replies.

Ciralia

Programmer
Oct 22, 2002
51
US
Does Visual Basic have any built in formulas for converting a hex to decimal. For example, the user inputs FF82, and I want the decimal form of this hex string.
 
MsgBox CLng("&H" + ("FF82"))

"Two strings walk into a bar. The first string says to the bartender: 'Bartender, I'll have a beer. u.5n$x5t?*&4ru!2[sACC~ErJ'. The second string says: 'Pardon my friend, he isn't NULL terminated'."
 
Hex$ will convert from dec to hex (obviously to string)

Code:
strHex = Hex$(16) 'strHex = "10"
[code]

and cint(&H10) will convert back

however
[code]
strHex = Hex$(16) 'strHex = "10"
debug.print cint(strhex) 'not desired result of 16 (prints 10)
strHex = "&H" & strHex 'Need to preend "&H"
debug.print cint(strhex) ' desired result of 16 
[code]

Take Care

Matt
If at first you don't succeed, skydiving is not for you.
 
...and given the thread heading, this also:

Decimal to hex

msgbox Hex(56)
 
Thanks guys for the conversion formulas, they do work. But I have just one more question about conversion. Is there also a formula for converting negative numbers into hex? I tried using the normal Hex( ) formula for the number -1 and the result it gave me was a lot of FFFFFFF, when it should have just been FF. So somewhere, the function to convert was not converting it correctly.
 
The answer you are getting is correct.

FF is normaly taken as being the Hex equivalent of 255 and not -1.

However if you want to 'bodge' your value of -1 to be FF in hex and -2 to be FE in hex etc. then you will need to use a bit mask on your answer.

Look at the difference between
msgbox Hex(-1)
msgbox Hex(-2)
and
msgbox Hex(-1 And &HFF)
msgbox Hex(-2 And &HFF)

Dave
 
Yes thank you that does work for the negatives. However, when I put in a mask of 8 hex characters &HFFFFFFFF, when I input the decimal number 10, I only get A as the hex result when it should be 0000000A. My value is stored as a string, so I'm not quite sure why the rest of the zeros aren't showing up.
 
Try this:
Format(Hex$(10), "&0000000&")

"Two strings walk into a bar. The first string says to the bartender: 'Bartender, I'll have a beer. u.5n$x5t?*&4ru!2[sACC~ErJ'. The second string says: 'Pardon my friend, he isn't NULL terminated'."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top