Building $lb from C

Primary tabs

I have a C string and I need to build a $lb from it.

This code works fine for strings shorter than 254 characters:

char *str = "some string";
int len = strlen(str);
int add = 2;
char *list = malloc(len + add + 1);
char lenChar = len + add;
sprintf(list, "%c\x01%s", lenChar, str);

Thought maybe someone can share the code for longer strings?

Replies

$lb(data1, data2, data3, ... dataN) is built as a string of item1 item2 item3 ... itemN

itemN:= <len> <type> <dataN>

assuming, you are on a little-endian CPU and

l1 = $length(data)
l2 = l1 + 1 // for type byte
l3 = l2 + 1 // for the length itself

then the length is as follows

if l1<=253 then len: <l3>
elseif l1<=65534 len:= <0> <l2-lowbyte> <l2-highbyte>
else len:= <0> <0> <0> <l2-lowbyte-loworderword> ... <l2-highbyte-highorderword>

And don't forget,
$lb(123) is not the same as $lb(1230/10), hence we have a $ls() function!