Convert char string in hex ?

vincenvincen Junior MemberPosts: 526
Hey

ok it's probably a stupid question but I'm unable to find the way to convert literally a char string in hex. For example I have a string 0AB0FF that I need to convert in hex type au $0A,$B0,$FF

Thanks

Vincèn

Comments

  • ColzieColzie Senior Member Posts: 470
    I believe hextoi will do what you need.
  • vincenvincen Junior Member Posts: 526
    Colzie wrote: »
    I believe hextoi will do what you need.
    hextoi ???*its supposed to do Hexa to decimal conversion !
  • ColzieColzie Senior Member Posts: 470
    The name is misleading if you've been using atoi and itoa for years.
    HEXTOI
    Converts an ASCII string containing the hexadecimal representation of a number to an unsigned 32-bit integer.
  • HedbergHedberg Junior Member Posts: 671
    although hextoi is supposed to return a 32 bit integer, it appears to me to actually return a 16 bit integer. So, when the argument given is 0AB0FF the integer returned appears to be $B0FF. If you can constrain the input hex_as_ascii strings to representing 16 bit numbers, you can use hextoi and then shift bits to get the answer you want.

    Here is a small section of code that will take the ascii hex you provide and populate an array with the decimal numbers you want. Remember, an integer can be represented as decimal or as hex interchangeably -- i.e. there is no difference to the process between decimal and hex.
    local_var integer icount
    local_var integer iii
    //hex_string contains the ascii hex representation you want as integers
    if(length_string(hex_string) % 2)
    {
    	hex_string = "'0',hex_string"  // pad the string with '0' if length is odd
    }			
    iCount = length_string(hex_string)/2
    for(iii= icount; iii ; iii--)
    {
    	nFromHex[iii] = hextoi(right_string(hex_string,2)) // nFromHex is an appropriate array to contain the result
    	hex_string = left_string(hex_string,length_string(hex_string)-2)
    }
    
    

    If you run this on the text you proposed, you get a three element array containing {$A,$B0,$FF}
    or {10,176,255} Type as either 8 bit character arrays or integer arrays as desired.

    edited:
    hextoi() does indeed return a 32 bit unsigned integer. But, if you assign the result to a 16 bit integer, as I dis -- well, that's clear.
    So, it's probably easier to use hextoi() on the whole string and then extract what is wanted by using bitwise and and shifting bits.
Sign In or Register to comment.