Padding hex values to be 2 characters instead of 1

I’m communicating with a serial device, sending commands in hex format.

In a for loop, where I’m updating each channel of the device so that they’re mapped 1:1 (It’ a router, so I’m mapping output 1 to input 1 and so on), the low numbered devices aren’t getting updated in the loop. That is:

var routersize as integer = 64

for i as integer = 0 to routersize -1
  Var hexString As String = "ff0040"+ i.ToHex + i.ToHex  +"ee"
  Try
    ' Decode the hex string into a byte string
    Var byteString As String = DecodeHex(hexString)
    
    ' Write the byte string to the serial port
    DetanglerSerial.Write(byteString)
    
  Catch error As IOException
    System.Beep
    MessageBox("The selected serial device could not be opened.")
  End Try
  
next

This should result in: ff 00 40 00 00 ee (without the spaces, I added them for readability). Instead it’s giving me: ff 00 40 0 0 ee – the two '0’s should be '00’s instead. As a result, the device is not updating the channel appropriately.

I also have a text field I can use, where I enter the number manually. If I enter “1” it doesn’t update channel 1. if I enter “01” it does. The problem is, this only works for the lowest numbers (0-9) because that happens to match the hex values (00-09). For 10-15 (A-F) toHex is generating “A” instead of “0A” so it doesn’t work.

So how do I get the hex value to be padded when the number I’m starting with would result in a non-padded 1-character hex value? Do I need to check the size and just add a 0 manually or is there another built-in function I can use to do this?

Maybe use i.ToHex(2)?

3 Likes

Thanks. Completely missed that somehow!

You should use i.ToHex(2) instead of i.ToHex

Edit: Sorry for that post. I was not shown any answers to the initial question before I had posted my reply :frowning: