如何将ASCII字符的十六进制值写入文本文件? [英] How does one write the hex values of a char in ASCII to a text file?

查看:211
本文介绍了如何将ASCII字符的十六进制值写入文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  void WriteHexToFile(std :: ofstream& stream,void * ptr ,int buflen,char * prefix)
{
unsigned char * buf =(unsigned char *)ptr; (int i = 0; i if(i%16 == 0){
stream<字首;
}

stream<< buf [i]<< '';
}
}

我试过做stream.hex,stream。 setf(std :: ios :: hex),以及在Google上搜索一下。我也试过:

  stream<< stream.hex<< (int)buf [i]<< ''; 

但这似乎并不奏效。



下面是一个当前产生的输出示例:

 ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ ÍÍÍ
ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
ÍÍÍÍ$ b b
ÍÍÍÍ$ $ $
$ bÍÍ我希望输出看起来像下面这样:



  FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00 
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00


解决方案

  #include< iostream> 
使用namespace std;
int main(){
char c = 123;
cout<<十六进制<< int(c)<< ENDL;
}

编辑::零填充:

  #include< iostream> 
#include< iomanip>
使用namespace std;
int main(){
char c = 13;
cout<<十六进制<< (2)<< setfill('0')<< int(c)<< ENDL;
}


Here is what I currently have so far:

void WriteHexToFile( std::ofstream &stream, void *ptr, int buflen, char *prefix )
{
    unsigned char *buf = (unsigned char*)ptr;

    for( int i = 0; i < buflen; ++i ) {
        if( i % 16 == 0 ) {
            stream << prefix;
        }

        stream << buf[i] << ' ';
    }
}

I've tried doing stream.hex, stream.setf( std::ios::hex ), as well as searching Google for a bit. I've also tried:

stream << stream.hex << (int)buf[i] << ' ';

But that doesn't seem to work either.

Here is an example of some output that it currently produces:

Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 

I would like the output to look like the following:

FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00

解决方案

#include <iostream>
using namespace std;
int main() {
    char c = 123;
    cout << hex << int(c) << endl;
}

Edit: with zero padding:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    char c = 13;
    cout << hex << setw(2) << setfill('0') << int(c) << endl;
}

这篇关于如何将ASCII字符的十六进制值写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆