在c++中打印字节流

Printing out byte stream in C++

本文关键字:字节流 打印 c++      更新时间:2023-10-16

在这个网站的帮助下,c++的int到字节数组,我有一个代码来序列化int到字节流。

来自整数值1234的字节流数据是大端格式的'x00x00x04xd2',我需要提出一个实用程序函数来显示字节流。这是我的第一个版本

#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);
}

我如何在屏幕上得到正确的值在十进制和十六进制?

For hex:

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

:

for (auto val : input) printf("%d ", val);