Convert hex to decimal and vice versa

Discussion in 'AutoCAD' started by Tony Burba, Jul 13, 2004.

  1. Tony Burba

    Tony Burba Guest

    This is probably ridiculously simple, but my math isn't so great anymore.

    How do I convert hexadecimal to decimal and back again? Or how can I simply
    increment a hexadecimal number by one unit? What I'm trying to do is access
    the Acad database sequentially by handle. Since the handles are strings
    representing hex numbers . . . well, you get it.

    Thanx in advance for any help.
     
    Tony Burba, Jul 13, 2004
    #1
  2. Tony Burba

    Jürg Menzi Guest

    Hi Tony

    This both I've found a long time ago in the ng:

    (defun Dec2Hex (Num / HexVal TmpNum TmpVal)
    (setq HexVal ""
    TmpNum Num
    )
    (while (< 0 TmpNum)
    (setq TmpVal (rem TmpNum 16)
    HexVal (strcat
    (if (< TmpVal 10)
    (chr (+ 48 TmpVal))
    (chr (+ 55 TmpVal))
    )
    HexVal
    )
    TmpNum (/ TmpNum 16)
    )
    )
    HexVal
    )

    (defun Hex2Dec (Stg / CurDgt PosCnt StgLen TmpLst TmpVal)
    (setq PosCnt 1
    StgLen (strlen Stg)
    )
    (repeat StgLen
    (setq CurDgt (strcase (substr Stg PosCnt 1))
    TmpVal (if (> (ascii CurDgt) 64)
    (- (ascii CurDgt) 55)
    (atoi CurDgt)
    )
    TmpLst (cons (* TmpVal (expt 16 (- StgLen PosCnt))) TmpLst)
    PosCnt (1+ PosCnt)
    )
    )
    (apply '+ TmpLst)
    )

    Cheers
     
    Jürg Menzi, Jul 13, 2004
    #2
  3. Tony Burba

    mataeux Guest

    this one function goes both ways,
    assume the decimal number to be a number type
    the hex equivalent is a string

    is it faster to use (expt 16 x) or to provide the value in a table as shown
    here?
    is there too much overhead in establishing the two tables in this function
    each time it is called?
    if you have to read all entities in a dxf file, for example, this function
    may not be the faster choice, but its worth testing

    (defun hexadecimal(q / h)
    (setq h'("0""1""2""3""4""5""6""7""8""9""A""B""C""D""E""F"))
    (cond
    ((numberp q) ;;; convert decimal to hex
    (setq q(fix q))
    (strcat(if(>(/ q 16)0)(hexadecimal(/ q 16))"")(nth(rem q 16)h))
    )
    ((=(type q)'STR) ;;; convert hex to decimal
    (setq q(strcase q))
    (repeat(strlen q)(setq q(strcat(substr q 2)" "(itoa(-
    16(length(member(substr q 1 1)h)))))))
    (setq q(read(strcat"("q")")))
    (apply'+(mapcar'*(reverse q)'(1 16 256 4096 65536 1048576 16777216
    268435456)))
    )
    )
    )
     
    mataeux, Jul 13, 2004
    #3
Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.