1

次の関数を cout でどのように記述しますか? 私の主な目的は、cout での使用方法を理解した後で、実際にすべての値をファイルに出力することです。std::hex が機能しません!

void print_hex(unsigned char *bs, unsigned int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf("%02x", bs[i]);
        //Below does not work
        //std::cout << std::hex << bs[i];
    }

}

編集:

cout 次のような値を出力します: r9{èZ[¶ôÃ

4

1 に答える 1

7

int にキャストを追加すると、あなたが望むことができると思います:

#include <iostream>
#include <iomanip>

void print_hex(unsigned char *bs, unsigned int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        std::cout << std::hex << static_cast<int>(bs[i]);
    }

}

int main() {
  unsigned char bytes[] = {0,1,2,3,4,5};
  print_hex(bytes, sizeof bytes);
}

これは、表示されていた文字ではなく、数値として強制的に印刷するために必要です。

于 2012-08-01T18:46:01.450 に答える