# Decimal-to-Hex Problem?

#### alfcen

##### Well-Known Member
Longtime User
Working on a wireless BT telescope controller that converts angles (right ascension and declination)
to an 8 digits hex string with two trailing zeros for a telescope to slew towards, say, a star.

B4X:
``````Sub Deg2Hex(x As Double, y As Double, grid As String) As String
Dim hexra, hexde As String
x = Round(x * 46603.378)
y = Round(y * 46603.378)
If y < 0 Then y = 16777216 + y
hexra = Bit.ToHexString(x) & "00000000"
hexra = hexra.SubString2(0,8).ToUpperCase
hexde = Bit.ToHexString(y) & "00000000"
hexde = hexde.SubString2(0,8).ToUpperCase
Select grid
Case "eqt"
Return "r" & hexra & "," & hexde
Case "azm"
Return "b" & hexra & "," & hexde
End Select
End Sub``````
The above routine works perfectly for most angles, but around x = 165 it gives wrong results.

The routine is the same as the one I once used with Basic4ppc, employing "hexra=bit.DecToHex(x)" with
no issues at all.

This raises the question whether "Bit.ToHexString" in B4A could contain a bug, such as omission of a leading
zero in a hex string. Or, my choice of conversion to Hex is a wrong one.

Cheers
Robert

#### agraham

##### Expert
Longtime User
Why is the algorithm taking the left hand side using SubString? Surely that will make, for example, angles of 1 and 16 return very similar results.

I'm sure there is no bug in ToHexString but it never returns a leading zero so if you are expecting an even number of digits you would need to do your own test and add a leading zero if necessary.

#### alfcen

##### Well-Known Member
Longtime User

Rather than digging deeper, I decided to add leading zeros as you suggested,
as, indeed, the scope expects hex strings in even pairs.

Thanks a lot for the trigger.

Android Question String HEX to Number HEX
Replies
3
Views
346
Android Code Snippet [B4X] Hex string to number
Replies
0
Views
2K
Android Code Snippet [B4X] HexToColor and ColorToHex
Replies
6
Views
4K