Printing out byte stream in C++

12,914

For hex:

for (auto val : input) printf("\\x%.2x", val);

For decimal:

for (auto val : input) printf("%d ", val);
Share:
12,914
prosseek
Author by

prosseek

A software engineer/programmer/researcher/professor who loves everything about software building. Programming Language: C/C++, D, Java/Groovy/Scala, C#, Objective-C, Python, Ruby, Lisp, Prolog, SQL, Smalltalk, Haskell, F#, OCaml, Erlang/Elixir, Forth, Rebol/Red Programming Tools and environments: Emacs, Eclipse, TextMate, JVM, .NET Programming Methodology: Refactoring, Design Patterns, Agile, eXtreme Computer Science: Algorithm, Compiler, Artificial Intelligence

Updated on June 26, 2022

Comments

  • prosseek
    prosseek almost 2 years

    With the help of this site, C++ int to byte array, I have a code to serialize int to byte stream.

    The byte stream data from integer value 1234 is '\x00\x00\x04\xd2' in big endian format, and I need to come up with an utility function to display the byte stream. This is my first version.

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    std::vector<unsigned char> intToBytes(int value)
    {
        std::vector<unsigned char> result;
        result.push_back(value >> 24);
        result.push_back(value >> 16);
        result.push_back(value >>  8);
        result.push_back(value      );
        return result;
    }
    
    void print(const std::vector<unsigned char> input)
    {
        for (auto val : input)
            cout << val; // <-- 
    }
    
    int main(int argc, char *argv[]) {
        std::vector<unsigned char> st(intToBytes(1234));
        print(st);
    }
    

    How can I get correct value on the screen both in decimal and hex?