Go Down

Topic: Cannot display byte as binary using sprintf() (Read 5921 times) previous topic - next topic

amundsen

I am trying to display a byte coming from an I2C slave in a binary form.

If I display the byte in decimal form it works:

Code: [Select]
i2c_start_wait(device_write_address);   // set device address and write mode
i2c_write(0x08);      // read address
i2c_rep_start(device_read_address);       // set device address and read mode
char statusBuffer[25];
sprintf(statusBuffer, "Chip status : %i", i2c_readNak());
Serial.println(statusBuffer);
i2c_stop();


The terminal displays this text: "Chip status : 132", which is correct for that I2c device.

However with this code:

Code: [Select]
i2c_start_wait(device_write_address);   // set device address and write mode
i2c_write(0x08);      // read address
i2c_rep_start(device_read_address);       // set device address and read mode
char statusBuffer[25];
sprintf(statusBuffer, "Chip status : %08b", i2c_readNak());
Serial.println(statusBuffer);
i2c_stop();


the terminal displays

"Chip status : " with no value afterwards althought I'd like to see "Chip status :  10000100"

What's wrong ?



PaulS

Code: [Select]
sprintf(statusBuffer, "Chip status : %08b", i2c_readNak());
I don't see b listed as a valid output type in my book, or here:
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
The art of getting good answers lies in asking good questions.

AWOL

You could print the value in hex.
Hex to binary is easy to do in your head, decimal to binary isn't quite so simple.

amundsen

I have tried this function but I got an "invalid conversion from 'const char*' to 'char' " error message.

Code: [Select]
//byte to binary string conversion
char byte_to_binary(int x) {
   char binaryString[8];
    for (int i = 0; i < 8; i++) {
      if ((x && pow(2, i)) == 1) {
        binaryString[7-i] = "1";
      } else {
        binaryString[7-i] = "0";
      }
   }
}

AWOL

#4
Jun 13, 2011, 01:50 pm Last Edit: Jun 13, 2011, 01:53 pm by AWOL Reason: 1
Code: [Select]
binaryString[7-i] = '1';


Your char function has no return statement.

I don't recommend the use of "pow" for simple integer powers of two.
If you're not happy with masks and shifts, use "bitRead"

amundsen

I am ok with masks and shifts but rather confused with char vs char*. bitRead is fine, I decided to convert each bit on the fly without storing data in a string, it's for display purposes only anyway.

Thanks for the advice.

AWOL

Quote
but rather confused with char vs char*.


You had a "char" array element, but you were trying to assign it a string - double quotes " implies string, and a string needs a char pointer (char*)
You should have been using single quotes, as I pointed in my earlier post, to assign a single char.

Go Up