 Convert from int to bin to string.

Hi there! I have bin searching the forum but could not find anything in the subject.

I is there a way to convert an integer value like 12 into a string in binary format like "00001100" ? The idea is to send the binary string value to a LCD display.

/E.T

;)

Mowcius

blodis, are you trying to convert a constant or a variable?

mowcius has the answer for a constant.

An answer for a variable would include the use of the bitRead() function inside a loop.

You could also use the LCD library to convert the number directly with

lcd.print(data, BIN);

although if I recall correctly, you do not get any leading binary zeros with this method.

Thank you for your replies fellows. TBAr I am using the LCD4bit library and it looks like passing a "BIN" to the function does not work. However I will try to use the bitread() approach instead.

Wish you all a Happy New Year!

/E.T

I had to do the same thing with a 16 bit word on an LCD. lcd.print(data, BIN); //this works, but like TBAr said, there are no leading zeros, so it looks messy when you're displaying a bunch of binary numbers. So I used the bitWrite(x,bitn) method. This just seems like it must use a lot of processor time because it has to write a value to the LCD for each bit one at a time, but it works.

lcd.setCursor(0,1); // set to first character bottom line
for (int i=15; i>=0; i--)
if (bitRead(value,i)==1) lcd.print ("1"); else lcd.print ("0");

this can be shortened to:

lcd.setCursor(0,1); // set to first character bottom line
for (int i=15; i>=0; i--)
if (bitRead(value,i)) lcd.print ("1"); else lcd.print ("0");

This just seems like it must use a lot of processor time because it has to write a value to the LCD for each bit one at a time, but it works.

Collect the bits in a buffer before printing…

char * int2bin(unsigned int x)
{
static char buffer;
for (int i=0; i<16; i++) buffer[15-i] = '0' + ((x & (1 << i)) > 0);
buffer ='\0';
return buffer;
}

void setup()
{
Serial.begin(115200);
for (int x = -10; x < 10; x++) Serial.println(int2bin(x));
}

void loop()
{
}