user10206903
user10206903

Reputation:

How to print uint8_t bytes array?

I have the following code:

uint16_t BufferSize = BUFFER_SIZE;
uint8_t Buffer[BUFFER_SIZE];

Buffer size is 64 bytes and is filled as:

Buffer[0] = 'P';
Buffer[1] = 'I';
Buffer[2] = 'N';
Buffer[3] = 'G';
Buffer[4] = 0;
Buffer[5] = 1;
Buffer[6] = 2;
Buffer[7] = 3;
Buffer[8] = 4;
.
.
.
Buffer[63] = 59;

I am trying to print the content of the Buffer using:

for( i = 0; i < BufferSize; i++ )
{

    PRINTF(Buffer[i]);

}

Also tried:

for( i = 0; i < BufferSize; i++ )
{
    PRINTF((const char*) Buffer[i]);
}

But it is not working.

Upvotes: 0

Views: 23248

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126867

  1. PRINTF all caps is not a standard C function; C is case-sensitive, so you want printf.
  2. Even so, when printing arbitrary strings you don't pass the string straight as the first argument to printf, as it may interpret some of its characters as placeholders for other arguments (say the string contains a %...). In general, pretty much any case when a printf-like function is invoked with anything but a string literal is suspect. So, you want printf("%s", (const char *)Buffer), or fputs((const char *)Buffer, stdout) (generally slightly more efficient).
  3. However, all these functions expect to work with NUL-terminated strings, not with counted buffers, so in your case they'll stop at the NUL just after PING. To actually output the whole buffer, you have to use an unformatted output function, such as fwrite: fwrite(buffer, BufferSize, 1, stdout).

Upvotes: 1

XQY
XQY

Reputation: 562

Just putchar is better and faster.

int putchar(int character);

returns EOF on error, or charater itself otherwise.

Upvotes: 0

Sandy
Sandy

Reputation: 903

You should refer to the syntax of printf. C treats small and capital letters differently so you should write something like this:

printf("%c", Buffer[i])

Upvotes: 1

Related Questions