6

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") 
2
  • 11
    Try endadd = Right("000000" & endadd,6) Commented Sep 5, 2016 at 2:03
  • 1
    Thanks it works like a charm. Cheers! Commented Sep 5, 2016 at 2:05

2 Answers 2

1

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
======================================================
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

Welcome to SO! When posting answers with code, please explain how your code solves the OP's problem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.