Binary input

Hi everybody!

I would like to read in binary files, then write them to another file.

I writed a code, what works perfectly, if I would like to just copy the file to another. But I want to make it a little other.

If I open a file in hex-editor I also can see the ASCII values. But I would like get the ONLY the hex values to the other file.

For example:

1
2
3
4
5
6
d5 57 4f ad 30 33 0b 4e 49 a7 05 18 c4 90 66 d8 45 ac 39 3e 7d f1 a8 02 80 
14 20 90 6e 20 12 38 0c 65 4a 28 d2 80 72 04 20 a9 4a 82 84 60 6a 0b 25 
59 4c 30 c8 69 c0 ec fa 36 ed 3a da b1 9a 82 02 e0 bb 7e 41 87 02 f6 10 34 
eb 95 93 63 01 6b 8d e1 d7 43 c3 df 92 5d 8a ed 57 61 4e 36 07 2a d7 56 2b 
b5 0e 55 83 b4 76 8c b7 61 77 0e c9 76 0c 81 1b 01 63 0c 8b 73 57 d5 6d 4c 
0c c2 0d 52 45 18 


How could I make it?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <fstream>
#include <iomanip>

void copy_bytes_hex( std::istream& in, std::ostream& out )
{
     // static_assert( std::numeric_limits<char>::digits == 8, "byte is not an octet" ) ;
     const int LINESZ = 96 ;

     out << std::hex ;

     char c ;
     int n = 0 ;
     while( in.get(c) )
     {
         out << std::setw(2) << std::setfill('0') << int(c) << ' ' ;
         n += 3 ;
         if( n > (LINESZ-3) ) { out << '\n' ; n = 0 ; }
     }

     if( n > 0 ) out << '\n' ;
}

bool copy_bytes_hex( const char* in_file, const char* out_file )
{
    std::ifstream fin( in_file, std::ios::binary ) ; // binary
    std::ofstream fout(out_file) ; // text

    copy_bytes_hex( fin, fout ) ;

    return fin.eof() && fout.good() ;
}
Thank you very much! :)

Your code is super, but the output is a little strange for me.

In hex editor:

ff d8 ff e0 20 10 4a 46 49 46 20 01 01 20 20 01 20 01 20 20 ff db 20 43 20 02 
02 02 02 02 02 02 02 02 02 03 02 02 02 03 04 03 02 02 03 04 05 04 04 04 04 
04 05 06 05 05 05 05 05 05 06 06 07 07


And the code gives the following for the same input:

ffffffff ffffffd8 ffffffff ffffffe0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 
ffffffff ffffffdb 00 43 00 02 02 02 02 02 02 02 
02 02 02 03 02 02 02 03 04 03 02 02 03 04 05 04 04 04 04 04 05 06 05 05 
05 05 05 05 06 06 07 07


Why happened this?

Thanks in advance!
The default char is a signed char, and got sign-extended when converted to an int.

Replace line 16 with
1
2
3
         // out << std::setw(2) << std::setfill('0') << int(c) << ' ' ;
          const unsigned char u = c ;
          out << std::setw(2) << std::setfill('0') << int(u) << ' ' ; 


(Your hex editor appears to be replacing null 00 with space 20.)
Thank you!!
Topic archived. No new replies allowed.