in reply to increment a hex number

If you have the numbers 0x000000, 0x010000, 0x020000 and 0x030000, then you can increment them using addition ($array[-1] += 1;) or using the pre- or post-increment operator (++$array[-1]; or $array[-1]++;).

my @nums = ( 0x000000, 0x010000, 0x020000, 0x030000, ); ++$nums[-1]; printf("0x%05X\n", $nums[-1]);

If you have the strings 0x000000, 0x010000, 0x020000 and 0x030000, then you need to convert them to numbers first using hex.

my @formatted_nums = ( '0x000000', '0x010000', '0x020000', '0x030000', ); $formatted_nums[-1] = sprintf("0x%05X\n", hex($formatted_nums[-1]) + 1 +); print("$formatted_nums[-1]\n");

Replies are listed 'Best First'.
Re^2: increment a hex number
by Anonymous Monk on May 10, 2010 at 22:30 UTC
    thanks for the input, but I cannot use 0x030001. I meant to say I need it to be increment from 0x030000 to 0x040000. ideas?
      Instead of using "+1" (or "++") for the "increment", you would use "+ 0x10000".

      That still involves treating the values as numbers rather than as strings:

      $_ = "0x030000\n"; s/0x([\da-f]+)/sprintf("%#.*x", length($1), hex($1) + 0x10000)/ei; print;
      That snippet will print "0x040000".
        thats dude....that will work!

        The code I do isn't much. I have a hex # converted to binary then using base64 math, I did some division built a key=>value such as 0x010000 => 65536 and thought this way seems silly and what if I miss a hex number. say my array only has 0x010000 to 0x050000....

      Like the others said.  BTW, the same arithmetic principle applies to decimal numbers, too:

      30000 + 10000 ------- 40000

      Or any other radix.