【问题标题】:Printing out bytes of a byte buffer to console output stream in hexadecimal notation (0xABCDEF)以十六进制表示法(0xABCDEF)将字节缓冲区的字节打印到控制台输出流
【发布时间】:2014-08-25 07:48:11
【问题描述】:

我知道关于这个主题有很多问题,但我认为找不到正确的关键字,所以我在问。

我想以十六进制表示法 (0xABCDEF) 将字节缓冲区的字节打印到控制台输出,但我不知道字节缓冲区是什么以及它用于什么?

我需要以下东西,我只是一个初学者,所以请尽量简单,我可以得到。 (在 C/C++ 中)

@param pBytes 指向字节缓冲区的指针 @param nBytes 字节缓冲区的长度(以字节为单位)

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

我需要那个功能。

你不必给出我需要你的答案,让我更容易! 谢谢!

【问题讨论】:

  • 我假设你想要两个字符的十六进制输出,这意味着零值高半字节写为0。 IE。 01020304...0E0F1011

标签: c++ c types bytebuffer hex


【解决方案1】:

使用 C++,您可以执行以下操作:

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

【讨论】:

  • @MervePehlivan 这是一个依赖于字节序的转换。正如我之前所说,如果每个字节输出两个字符(一个用于高半字节,一个用于低半字节),会更清楚。这个答案做到了,接受的答案没有。 (+1,顺便说一句,尼克)
【解决方案2】:

使用hex操纵器

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2017-09-13
    • 2015-08-08
    • 1970-01-01
    • 2023-04-07
    • 2013-01-18
    相关资源
    最近更新 更多