Reputation: 137
I want to convert hexadecimal which are 3 digits long into 6 digits. For example 12F shd be 00012F. I tried this code but it didnt work.
endadd = Format(endadd, "000000")
Upvotes: 6
Views: 7341
Reputation: 1
You should implement following function
Public Function HexByte2Char(ByVal Value As Byte) As String
' Return a byte value as a two-digit hex string.
HexByte2Char = IIf(Value < &H10, "0", "") & Hex$(Value)
End Function
Usage
Dim s As String
s = HexByte2Char(dec_number)
Upvotes: 0
Reputation: 9461
As Scott Craner pointed out, a simple Right("000000" & endadd,6)
will work perfectly well, but Right$("000000" & endadd,6)
is slightly faster.
Furthermore, from a performance perspective, it really depends on whether the original source of the endadd
value is a String or Numeric.
'CONCAT String Approach
'If the hex source is a string, then this is the most efficient approach
formattedHex = Right$("000000" & "12F", 2)
'CONCAT Numeric Approach
'But if the hex source is a numeric, then this hex conversion AND concatenation is required, but it is SLOW
formattedHex = Right$("000000" & Hex$(&H12F), 2)
'ADDITION/OR Numeric Approach
'When the hex source is numeric it is more efficient to use a bit trick to add AND convert
formattedHex = Right$(Hex$(&H1000000 + &H12F), 2)
formattedHex = Right$(Hex$(&H1000000 Or &H12F), 2)
Results from a 10m operation loop:
Approach | Using Right | Using Right$ |
==========================+=============================
CONCAT String Approach | 1.59s | 1.40s
CONCAT Numeric Approach | 2.63s | 2.33s
ADDITION Numeric Approach | 1.74s | 1.60s
======================================================
Upvotes: 1