이진 파일을 읽고 16 진수 표현으로 변환하는 데 문제가 있습니다.C++ 이진 파일을 읽고 16 진수로 변환
지금까지 시도했습니다 무엇:
ifstream::pos_type size;
char * memblock;
ifstream file (toread, ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the complete file content is in memory" << endl;
std::string tohexed = ToHex(memblock, true);
std::cout << tohexed << std::endl;
}
진수로 변환 :
string ToHex(const string& s, bool upper_case)
{
ostringstream ret;
for (string::size_type i = 0; i < s.length(); ++i)
ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << (int)s[i];
return ret.str();
}
결과 : 53514C69746520666F726D61742033
합니다.
나는 헥스 편집기를 사용하여 원본 파일을 열고이 그것을 보여줍니다 무엇 : C를 사용하여 동일한 원하는 출력을 얻을 수있는 방법이
53 51 4C 69 74 65 20 66 6F 72 6D 61 74 20 33 00
04 00 01 01 00 40 20 20 00 00 05 A3 00 00 00 47
00 00 00 2E 00 00 00 3B 00 00 00 04 00 00 00 01
00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 A3
00 2D E2 1E 0D 03 FC 00 06 01 80 00 03 6C 03 D3
있습니까 ++?
(로브로) 솔루션 작업 :
이...
std::string tohexed = ToHex(std::string(memblock, size), true);
...
string ToHex(const string& s, bool upper_case)
{
ostringstream ret;
for (string::size_type i = 0; i < s.length(); ++i)
{
int z = s[i]&0xff;
ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << z;
}
return ret.str();
}
"memblock은 처음 15 바이트 만 포함하고 null 바이트 (16 번째)에서 멈 춥니 다."뭐라고할까요? 나는 당신이'memblock'의 내용을 출력하는 곳을 보지 못했습니다. 나는'memblock'이 전체 파일을 포함하고 있다고 의심하지만 우리에게 보여주지 않는 코드는 그 내용을 잘못 해석하고있다. 오류를 나타내는 가장 작은 완전한 프로그램으로 프로그램을 축소하고 해당 프로그램을 질문에 게시하십시오. http://sscce.org –
@ Rob 당신은 더 명확히하기 위해 처음 15 바이트를 다시 게시해야합니까? – technology
이것이 숙제이거나 일종의 학습 과제라고 가정하면 다음과 같은 몇 가지 힌트가 있습니다 : (1) 방금 while 루프를 놓치고 있습니다. (2) 방금 연 스트림에서 tellg()를 호출합니다. 조숙하다. – dasblinkenlight