25

Right now, I'm learning how to interface SICStus Prolog with C code.

I would like to have/use/see a C implementation of "Hamming weight" of arbitrary-sized integers in SICStus Prolog version 4.

It seems to me that I need C functions for testing term types (SP_is_integer) and C functions for accessing Prolog terms (SP_get_integer, SP_get_integer_bytes).

However, I'm not sure how to use SP_get_integer_bytes in a portable, robust fashion. Could you please point me to some well-crafted solid C code doing just that?

false
  • 10,182
  • 12
  • 93
  • 182
repeat
  • 19,449
  • 4
  • 51
  • 152

1 Answers1

14

Use it something like this:

SP_term_ref tr = ... some term ...
int native = 0; // want portable, little endian
size_t buf_size = 0;

if (!SP_get_integer_bytes(tr, NULL, &buf_size, native)
    // if buf_size was updated, then there was not really an error
    && buf_size == 0)
{
    // Something wrong (e.g., not an integer)
    return ERROR;
}

// here buf_size > 0
void *buffer = SP_malloc(buf_size);

if (buffer == NULL)
{
    return ERROR;
}

if (!SP_get_integer_bytes(tr, buffer, &buf_size, native))
{
    // Something wrong. This would be surprising here
    error();
}

// Here buffer contains buf_size bytes, in
// twos-complement, with the least significant bytes at lowest index.
// ... do something with buffer ...

// finally clean up
SP_free(buffer);
Markus Safar
  • 5,899
  • 5
  • 25
  • 41
Per Mildner
  • 8,656
  • 19
  • 27
  • 2
    This works with any integer. This works with any buffer (e.g. you could use a static buffer that is usually large enough, and then allocate a dynamic buffer when the integer is too large to fit in the static buffer). – Per Mildner Mar 04 '15 at 08:18