-3

I know there are a lot of questions about this topic but I think a couldn't find the right keywords so I'm asking.

I want to print out bytes of a byte buffer to console output in hexadecimal notation (0xABCDEF) but i don't know what is the byte buffer and it using for what?

I need the following things and I'm just a beginner so please make it simple that i can get. ( in c/c++)

@param pBytes pointer to the byte buffer @param nBytes length of the bytes buffer in bytes

void PrintBytes(const char* pBytes, const uint32_t nBytes);

I need that functions.

You don't have to giving the answers i need you to make it easier for me! Thank you!

Clifford
  • 88,407
  • 13
  • 85
  • 165
someWhereElse
  • 15
  • 2
  • 6
  • I assume you want two-char hex output, which means zero-valued high-nibbles are written as `0`. I.e. `01020304...0E0F1011` etc. – WhozCraig Aug 25 '14 at 07:56

2 Answers2

7

With C++ you could do something like this:

#include <iostream>
#include <iomanip>

void PrintBytes(
    const char* pBytes,
    const uint32_t nBytes) // should more properly be std::size_t
{
    for (uint32_t i = 0; i != nBytes; i++)
    {
        std::cout << 
            std::hex <<           // output in hex
            std::setw(2) <<       // each byte prints as two characters
            std::setfill('0') <<  // fill with 0 if not enough characters
            static_cast<unsigned int>(pBytes[i]) << std::endl;
    }
}
Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
  • 1
    @MervePehlivan thats an endian-dependent transformation. and as I said earlier, it would be clearer if you output two chars per byte (one for high-nibble, one for low nibble). This answer does that, the accepted answer does not. (+1, btw, Nik) – WhozCraig Aug 25 '14 at 09:08
2

Use hex manipulator

#include <iomanip>
#include <iostream>

void PrintBytes(const char* pBytes, const uint32_t nBytes) {
    for ( uint32_t i = 0; i < nBytes; i++ ) {
        std::cout << std::hex << (unsigned int)( pBytes[ i ] );
    }
}
borisbn
  • 4,988
  • 25
  • 42