Search code examples
capl

stored hex values in notepad file with .ini extension how to read it in hex only via CAPL


I have stored hex values in a text file with .ini extension along with address. But when i read it, it will not be in hex format it will be in character so is there any way to read value as hex and store it in byte in C language or in CAPL script?


Solution

  • I assume that you know how to read a text file in CAPL...

    You can convert a hex string to a number using strtol(char s[], long result&):long. See the CAPL help (CAPL Function Overview -> General -> strol):

    The number base is

    • haxadecimal if the string starts with "0x"
    • octal if the string starts with "0"
    • decimal otherwise

    Whitespace (space or tabs) at the start of the staring are ignored.

    Example:

    on start
    {
        long number1, number2;
    
        strtol("0xFF", number1);
        strtol("-128", number2);
    
        write("number1 = %d", number1);
        write("number2 = %d", number2);
    }
    

    Output:

    number1 = 255
    number2 = -128
    

    See also: strtoll(), strtoul(), strtoull(), strtod() and atol()

    Update:

    If the hex string does not start with "0x"...

    on message 0x200
    {
      if (this.byte(0) == hextol("38"))
        write("byte(0) == 56");
    }
    
    long hextol(char s[])
    {
      long res;
      char xs[8];
    
      strncpy(xs, "0x", elcount(xs)); // cpy "0x" to 'xs'
      strncat(xs, s, elcount(xs));    // cat 'xs' and 's'
      strtol(xs, res);                // convert to long
    
      return res;
    }