users-prolog
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

hexstring help


From: Renaud Mariana
Subject: hexstring help
Date: Wed, 30 Jan 2002 11:19:25 GMT+1

Hi all,

does anybody has a predicate that unifies a list of bytes to
a hexstring (atom) efficiently ?

ex: hexstring('010A', [1,10]). returns true.

the one I propose with the C interface is not elegant,
requires a lot of allocations and also may crash if the list
is too long .
Thanks.

Renaud Mariana

//-------------------------------------------------------

// fill buf with byte-elements of list
// buf must be allocated
int
getCharsFromList(PlTerm list, unsigned char* buf)
{
        PlTerm* pterm = (PlTerm*)list;
        int n = 0;


        for(; pterm != (PlTerm*)NIL_WORD; pterm = (PlTerm*)pterm[1])
                {
                        pterm = Rd_List( (PlTerm)pterm);
                        if(pterm == 0) break;
                        buf[n++] = Rd_Byte( pterm[0])&0xff;
        }

        return n;
}

// test
// hexstring('A0000000300002FFFFFFFF8900010001', L ).
// hexstring( T,
[160,0,0,0,48,0,2,255,255,255,255,137,0,1,0,1]).



// conversion: atom <-> list of bytes
Bool
hexstring (PlTerm atom, PlTerm list)
{
        int i = 0, t, length;
        char *hexDigits = "0123456789ABCDEF";
        unsigned char buf[1024];
        char str[2048], *str2;
        PlTerm term[1024];


        if(Blt_Non_Var(list)) {
                length = getCharsFromList(list, buf);
                str2 = str;

                for ( i = 0; i < length; ) {
                        t = buf[i++];
                        *str2++ = hexDigits[(t >> 4) & 0x0F];
                        *str2++ = hexDigits[ t & 0x0F];
                }
                *str2 = 0;
                return Un_String_Check(str, atom);
        }

        if( Blt_Var(atom))
                Pl_Err_Instantiation();

        str2 = Rd_String_Check(atom);
        length = strlen(str2);

        if ((length % 2) == 1) {
                sscanf(str2++, "%01x", &t);
                term[i++] = Mk_Byte(t);
        }

        for ( ; *str2 ; str2+=2 ) {
                sscanf(str2, "%02x", &t);
                term[i++] = Mk_Byte(t);
        }

 return Un_Proper_List_Check(i, term, list);
}
//-------------------------------------------------------



______________________________________________________
BoƮte aux lettres - Caramail - http://www.caramail.com


reply via email to

[Prev in Thread] Current Thread [Next in Thread]