Formatting

howto format a character to an ascii value?
howto format an integer to a binary?

could not find anything in the docs…

format("%c", intvalue) will return a string with the byte value specified. This is commonly used to pass values to an i2c write function, for example.

Is that what you needed?

thanks Hugo,
that’s my first question.
my second is something like format("%b", 10) =1010 (or “1010”)

I don’t think there’s a built in formatter for binary. Here’s one way of doing it:

function binstring(val) { local str = ""; while(val) { str = ('0' + (val & 1)).tochar() + str; val = val >> 1; } return str; }

Thanks philmy,

You saved me a lot of time, trying to find a solution like this…

Another option that allows for varying bit widths but also display the value in2/4/6 or 8 hex digits:

function ShowBinary(value, width) { local m1 = "0x%02X: "; if ((width == 0) || (width > 32)) return (-1); local mask = (1 << (width - 1)); if (width > 24) m1 = "0x%08X: "; else { if (width > 16) m1 = "0x%06X: "; else { if (width > 8) m1 = "0x%04X: "; }} local m2 = format(m1, value); for (local pos = 0; pos < width; pos++) { m2 += format("%c",((value & mask) != 0) ? 0x31 : 0x30); mask = (mask >> 1); } return m2; }

great!
Was trying to do the same. But I’m not able to do it this efficient.
Thanks ammaree!