Reverse of Hex? Need to get back to Byte

# Thread: Reverse of Hex? Need to get back to Byte

1. Member
Join Date
Dec 1969
Posts
49

## Reverse of Hex? Need to get back to Byte

I have a function that converts an array of byte value to HEX for storage as a string...<BR><BR>For lCount = 0 To UBound(bytOut)<BR>sTemp = sTemp & Right("0" & Hex(bytOut(lCount)), 2)<BR>Next<BR><BR>Which produces something like this...<BR><BR>08F2402EC2DFEBE2BBBFFABF47CBA5358C9 B1B86FAE522A645644E7800B7BD7A<BR><BR>Now I&#039;m having the HARDEST time just doing the reverse and converting back from HEX to Bytes. I would assume we can use CByte along with whatever the reverse of Hex is, pls help, thank so much!<BR><BR>Oh and btw, I start with a normal text string and use the following function to convert to an array of bytes...<BR><BR> sPlain = "normaltextstring"<BR> lLength = Len(sPlain)<BR> ReDim bytOut(lLength-1)<BR> For lCount = 1 To lLength<BR> bytOut(lCount-1)=CByte(AscB(Mid(sPlain,lCount,1)))<BR> Next

2. Senior Member
Join Date
Dec 1969
Posts
5,955

## Should be rather straightforward. ...

...Two hex digits (or nibbles) make one byte, so make sure your hex string has an even number of characters - left pad with a zero if necessary. Then you just loop through the string with step 2 and convert each two characters into a byte. Something like this (untested!!!):<BR><BR>Dim sHex, arrBytes<BR><BR>sHex = "0123456789ABCD"<BR><BR>ReDim arrBytes(Len(sHex))<BR><BR>For nIdx = 1 To Len(sHex) Step 2<BR>&nbsp;&nbsp;arrBytes(Floor(nIdx / 2)) = CInt("&H" & Mid(sHex, nIdx, 2))<BR>Next<BR><BR>I&#039;m not a VBScript person myself, so there may be a few glaring mistakes in this code. My arrBytes is zero-based, which I think is what arrays in VBScript normally are. If not, then you have to amend that bit.<BR><BR>Oliver.

3. Senior Member
Join Date
Dec 1969
Posts
5,955

## Small mistake in my code: ...

...<BR><BR>ReDim arrBytes(Len(sHex) / 2)<BR><BR>The byte array is half as long as the hex string.<BR><BR>Oliver.

4. Member
Join Date
Dec 1969
Posts
49

## RE: wow thanks!

That helped so much!<BR><BR>Since the function "Floor()" doesn&#039;t exist in VBScript, I had to modify the function a bit, I just added an internal counter in the loop such as...<BR><BR>count = 0<BR>For nIdx = 1 To Len(sHex) Step 2<BR> arrBytes(count) = CInt("&H" & Mid(sHex, nIdx, 2))<BR>count = count + 1<BR>Next<BR><BR>Ya that&#039;s very cool, I had no understanding of what bytes and hex were until now =)

5. Senior Member
Join Date
Dec 1969
Posts
96,118

## Still wrong...

If the hex string is (say) 10 characters long, then you will do<BR> ReDim arrBytes(5)<BR>Yes???<BR><BR>But *that* is a *SIX* element array.<BR><BR>Should be ReDim arrBytes(Len(sHex)/2-1)<BR><BR>NOW what do you do if the string is *NINE* characters long?<BR><BR>

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•