Convert an array of bytes to a string

B

Bit Twiddler

I am having a tough time doing this is a "nice" manner.

For example, if the byte vales in the array are 0x4D, 0x00, 0xFF, the
resulting string should look like: "4D00FF"

Thanks for any pointers,
BT
 
S

Steve Rindsberg

I am having a tough time doing this is a "nice" manner.

For example, if the byte vales in the array are 0x4D, 0x00, 0xFF, the
resulting string should look like: "4D00FF"

Hex(Byte) will give you the individual conversions you want.

Something like this:


Sub ByteMyString()

Dim ByteMe(1 To 4) As Byte
Dim x As Long
Dim sString As String

ByteMe(1) = 42
ByteMe(2) = 255
ByteMe(3) = 0
ByteMe(4) = 16


For x = 1 To UBound(ByteMe)
If ByteMe(x) = 0 Then
' ordinarily it'd give you "0" so:
sString = sString & "00"
Else
sString = sString & Hex(ByteMe(x))
End If
Next

MsgBox sString

End Sub
 
K

Karl E. Peterson

Steve said:
For x = 1 To UBound(ByteMe)
If ByteMe(x) = 0 Then
' ordinarily it'd give you "0" so:
sString = sString & "00"
Else
sString = sString & Hex(ByteMe(x))
End If
Next

That's gonna run into issues with small values (less than &h10). Suggested
modification:

sString = sString & Right$("0" & Hex$(ByteMe(x)), 2)

Later... Karl
 
S

Steve Rindsberg

That's gonna run into issues with small values (less than &h10). Suggested
modification:

sString = sString & Right$("0" & Hex$(ByteMe(x)), 2)

Later... Karl

Undubitably. Thanks!
 
B

Bit Twiddler

Just wanted to thank Karl & Steve for their great responses - thanks guys!

-BT
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top