Shop OBEX P1 Docs P2 Docs Learn Events
How do I convert a text string to a HEX string? — Parallax Forums

How do I convert a text string to a HEX string?

Don MDon M Posts: 1,652
edited 2014-04-25 10:53 in Propeller 1
I have this 32 character string:
DAT

  Text byte "cc9a67d9fb998b18922e015a35af0780"


and I want to convert it into 16 HEX bytes into a byte buffer called Temp[40] so that Temp[0] = $cc, Temp[1] = $9a, Temp[2] = $67 and so on.

How do I do this?

Thanks.
Don

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2014-04-24 20:13
    pri hexConvert( fromPtr, toPtr, count) | i, t1, t2
       repeat i from 0 to count-1
          t1 := byte[fromPtr++] - "0"   ' get most significant nibble and adjust for ASCII zero
          if t1 > 9
             t1 := t1 - constant("a" - "0"  - 10)   ' if in range "a".."f", correct value for that
          t2 := byte[fromPtr++] - "0"   ' get least significant nibble and adjust for ASCII zero
          if t2 > 9
             t2 := t2 - constant("a" - "0" - 10)   ' if in range "a".."f", correct value for that
          byte[toPtr++] := t1 << 4 + t2   ' put nibbles together into a byte and store
    
    This can be done more efficiently, but the above is straightforward and easy to understand
  • JonnyMacJonnyMac Posts: 9,105
    edited 2014-04-24 20:30
    Here's what I came up with. This uses a method that lets you convert 1 to 8 hex ASCII characters (each is a nibble) to a value.
    dat
    
      TestStr       byte    "cc9a67d9fb998b18922e015a35af0780", 0
    
    
    pub main | idx
    
      term.start(RX1, TX1, %0000, 115_200)
      pause(10)
    
      ' press key to start
    
      term.rxflush
      term.rx
    
      ' convert array
    
      repeat idx from 0 to 15
        buf[idx] := ascii_to_hex(@TestStr[idx << 1], 2)
    
      ' display
    
      term.tx(CLS)
      term.str(@TestStr)
      term.tx(CR)
      term.tx(CR)
    
      repeat idx from 0 to 15
        term.hex(buf[idx], 2)
        term.tx(" ")
    
      repeat
        waitcnt(0)    
    
    
    pub ascii_to_hex(p_str, n) : value | c
    
    '' Convert n hex ascii chars at p_str to value
    
      repeat n
        c := ucase(byte[p_str++])
        c := lookdown(c: "0123456789ABCDEF")
        if (c > 0)
          value <<= 4
          value += --c
        else
          quit
    
      return value
    
    
    pub ucase(c)
    
    '' Convert lowercase c to uppercase
    
      if ((c => "a") and (c =< "z"))
        c -= 32
    
      return c
    
  • Beau SchwabeBeau Schwabe Posts: 6,566
    edited 2014-04-24 20:54
    This will work also ...
        repeat i from 0 to 15
          Temp[i] := lookdownz(byte[@Text][i*2+1]:"0123456789abcdef")
          Temp[i] += lookdownz(byte[@Text][i*2]:"0123456789abcdef")<<4
    
  • Don MDon M Posts: 1,652
    edited 2014-04-25 10:53
    Thanks guys. Much appreciated.
Sign In or Register to comment.