How do I open a file then convert each character to ASCII hexadecimal ...

Hello,

How do I open a file then convert each character to ASCII hexadecimal and save it to a string to return from the openBinaryFile() function. string OpenBBByFile( string filename);)...by using istringstream and ostringstream..

Thanks
daskino12Asked:
Who is Participating?
 
AxterConnect With a Mentor Commented:
This version should about do it.

#include <fstream>
#include <iomanip>
#include <sstream>

string openBinaryFile(const string &filename)
{
      ifstream fIn;
    fIn.open(filename.c_str(), ios_base::binary | ios_base::in );
      const int MaxHexNumbers = 15;
      int QtyHex = 0;
      std::stringstream ss;
      int c;
      while (! fIn.eof() && (c = fIn.get()) > 0) {
            ss << setfill('0') << setw(2) <<  std::hex << c;
            ss << " ";
            ++QtyHex;
            if (QtyHex == MaxHexNumbers)
            {
                  ss << endl;
                  QtyHex = 0;
            }
      }
      return ss.str();
}
0
 
dualsoulCommented:
Just use OpenFile()  API function to open your file
And then user ReadFile to read data from it
And convert it to anything you want, what's problem?
You can wrapper for file operations and use as some File class for instance;
0
 
havman56Commented:
see the below code

std::ofstream *op_stream_ptr;

// this u just think  ok....
op_stream_ptr=new  fstream

T data;

   (*op_stream_ptr).open("istream_data.txt", std::ios_base::trunc);
   (*op_stream_ptr)<< data;
   (*op_stream_ptr).close();

std::ifstream *ip_stream_ptr;

// this u just think  ok....
ip_stream_ptr=new  ifstream

T exp_data;

  (*ip_stream_ptr).open("istream_data.txt");
   (*ip_stream_ptr).clear(std::ios_base::goodbit);
   (*ip_stream_ptr) >> exp_data;
   (*ip_stream_ptr).close();


u really dont need ostring stream and istring stream when u operate on file stream
ofstream and if stream will do for u

data may be anything that why it is T u can have even stream as T*

just do new u will get everything done

good bit for making sure the stream is good state.










0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
daskino12Author Commented:
Hello all,

Thanks for the help.  Let's say the question stays the same but with a little bit of more details:  The function openBinaryFile() should return a string holding the contents of the input fie, coveted to hexadecimal with theollowing format:

- twohexadecimal ccters for each byte (like  0A)
-one space between every two hex characters (like 61 52)
-15 bytes of hexadecimal characters  each line

so..it's like...when opening a binary file, convert each character to ASCII hexadecimal and se i to a trng to rturn from the openBinaryFile() function.

THanks
0
 
daskino12Author Commented:
Hello,

I am sorry..that's assumed we have string openBinaryFile( string filename);..

THanks

0
 
DanRollinsConnect With a Mentor Commented:
Here ya go!
1) Open the file
2) Read each byte
3) Convert to two-digits of hex
4) add to destination string
5) add either a space to CRLF (end of line) depending upon if 15th in the line

6) Turn in to the prof for an A

#include<iostream>
#include<fstream>
using namespace std;

bool FileToHexString( char* szFilename, string& sOutput )
{
      unsigned char b;      
      ifstream fIn;
      fIn.open( szFilename, ios_base::binary | ios_base::in );
      if ( ! fIn.is_open() ) {
            return( false );
      }
      int nCnt= 0;
      while (! fIn.eof() ) {
            fIn >> b;
            char sTmp[3];
            sprintf( sTmp,"%02X", b );
            sOutput += sTmp;
            nCnt++;
            if ( (nCnt % 15)  == 0) sOutput += "\r\n";
            else                    sOutput += " ";
      }
      if ( (nCnt % 15) != 0) {
            sOutput += "\r\n";
      }
      return( true );
}
//------------------------------- validation code
void main(void)
{
      string s;
      bool fRet= FileToHexString( "c:\\temp\\TheData.txt", s );
      cout << s.c_str();
}

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
THis will be rather slow on very large file.  There is a truck that will speed it up.  Interested?

-- Dan
0
 
DanRollinsCommented:
Correction: I forgot to add
    fIn.close();
before the return in the FileToHexString() fn.
-- Dan
0
 
daskino12Author Commented:
Hello,

I am sorry but I still dont quiet get the code you have (kinda too complicated for me).  I have this function, "string openBinaryFile( string filename)" so i want to go from there.....anyone?

Thanks
0
 
AxterCommented:
Here's a modified version of Dan's code.
0
 
AxterCommented:
Let's try that again :-)

std::string CharToHex(char c)
{
   std::stringstream ss;
   ss << std::hex << (int)c;
   return ss.str();
}

string openBinaryFile(const string &filename)
{
    unsigned char b;    
      ifstream fIn;
      string ReturnValue;
    fIn.open(filename.c_str(), ios_base::binary | ios_base::in );
      while (! fIn.eof() ) {
            fIn >> b;
            ReturnValue += CharToHex(b);
      }
      return ReturnValue;
}
0
 
AxterCommented:
Although this function has the format you requested, Dan's original code and format is more optimize.

In the above function, the string is being return by value.  Most string implementations use reference counters, so you probably will not see much of a difference.
However, in general you should try to avoid returning complex object by value, and instead try to pass in by reference the object to be modified.
0
 
daskino12Author Commented:
Hello all,

Here is my final code and it works:) Thank you all so much..however, can you please help me with this code?  I tried to save the file by using this function "void saveBinaryFile( string text, string filename)"

My working file:
       StringBuffer hexContent = new StringBuffer();
     try
     {
       BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
       int byteRead;
       int count = 0;
       while ((byteRead = in.read()) != -1) {
              count++;
         String hex = Integer.toString(((byte)byteRead & 0xff) + 0x100,16).substring(1);
         hexContent.append(hex);
       if (count < 15){
       hexContent.append(" ");
       }
       if (count == 15 ){
       hexContent.append("\n");
       count = 0;
       }
       }
       in.close();
     }

     catch(IOException e)
     {
     }
     
     return hexContent.toString();
     
     
} // openBinaryFile()


My not working file:

      public static void saveBinaryFile( String text, String filename ) {
      
            // YOUR HOMEWORK 9 CODE HERE
       try
       {
           FileOutputStream fos = new FileOutputStream(filename);
           fos.write(new java.math.BigInteger(text, 16).toByteArray());
           fos.close();
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }            
  }      

What void saveBinaryFile( string text, string filename) does is upon saving the binary file, it should convert the hex bytes back into binary and write the binary file.

Please help..

Thanks
0
 
daskino12Author Commented:
Hello,

I am sorry..that's for Java..i am still trying the C++ one..

Thanks
0
 
daskino12Author Commented:
Hello,

It doesn't seem to be working.  My function is "public static String openBniaryFile( String filename);"  and I will need to use istringistream and ostringstream.  To convert a hexadecimal number in a string to a number in C++, I can use the "hex" steram manipulator with an istringsteam.    It also needs the following formats:

-two hexadecimal characters for each byte (example: 0A)
-one space between every two hex characters (example: 61 62)
-15 bytes of hexadecimal characters in each line

for example,

Input:
race carrot or race car
I prefer pi
kayak

Open as binary:

72 61 63 65 20 63...

Thanks
0
 
AxterCommented:
>>It doesn't seem to be working.  
Exactly what is not working?
Please provide details so that we can better help you.

The more information you provide, the better.
0
 
AxterCommented:
Here's a modified version with extra requirements.

std::string CharToHex(char c)
{
   std::stringstream ss;
   ss << std::hex << (int)c;
   return ss.str();
}

string openBinaryFile(const string &filename)
{
    unsigned char b;    
      ifstream fIn;
      string ReturnValue;
    fIn.open(filename.c_str(), ios_base::binary | ios_base::in );
      const int MaxHexNumbers = 15;
      int QtyHex = 0;
      while (! fIn.eof() ) {
            fIn >> b;
            ReturnValue += CharToHex(b);
            ReturnValue += " ";
            ++QtyHex;
            if (QtyHex == MaxHexNumbers)
            {
                  ReturnValue += "\n";
                  QtyHex = 0;
            }
      }
      return ReturnValue;
}
0
 
daskino12Author Commented:
Hello,

Well, I can't add the following in addition to the function "string openBinaryFile( string filename)" (it has to be like this..)..

std::string CharToHex(char c)
{
   std::stringstream ss;
   ss << std::hex << (int)c;
   return ss.str();
}

Do you know how to do it without adding above code?

Thanks
0
 
daskino12Author Commented:
Hello,

I was wondering, maybe i can use something called "setw()", will it be easier?

Thanks
0
 
AxterCommented:
Just put the code inside the loop.
Example:

string openBinaryFile(const string &filename)
{
    unsigned char b;    
      ifstream fIn;
      string ReturnValue;
    fIn.open(filename.c_str(), ios_base::binary | ios_base::in );
      const int MaxHexNumbers = 15;
      int QtyHex = 0;
      while (! fIn.eof() ) {
            fIn >> b;
            std::stringstream ss;
            ss << std::hex << (int)b;
            ReturnValue += ss.str() + " ";
            ++QtyHex;
            if (QtyHex == MaxHexNumbers)
            {
                  ReturnValue += "\n";
                  QtyHex = 0;
            }
      }
      return ReturnValue;
}
0
 
daskino12Author Commented:
Hello,

I have one more question about SavingbinaryFile.  I have this function, void saveBinaryFile( string text, string filename), where the parameter filename is the name of the input or the output file, as the case may be, and where the parameter text is the hexadecimal text to be written to the file.  I am doing the whole project called Text Editor and SaveBinaryFile is  one of my functions.  Within the TextEditor, the hex bytes can be edited, and upon saving the binary file, it should convert the hex bytes back into binary and write the binary file....i am thinking using "Integer.parseInt(hexByte, 16) for the convsion...any help to do this?

Thanks a lot
0
 
AxterCommented:
I think you should ask this in a seperate question.

This question already has to many comments to keep track off.

If you post a new question, remember to give us much details as possible.
The above comment is ambiguous, and it would be hard to answer your question with out more details.
0
 
daskino12Author Commented:
Hello,

OpenBinary is almost working:)  But the format is a bit off..like..it's 15 bytes of hexadecimal characters in each line...and..it seems the conversion is a bit different...

Input:

race carrot or race car
I prefer pi
kayak

After Open as binary (working one)
72 61 63 65 20 63 61 72 72 6f 74 20 6f 72 20
72 61 63 65 20 63 61 72 0a 49 20 70 72 65 66
65 72 20 70 69 0a 6b 61 79 61 6b

the one using your code:

72 61 63 65 63 61 72 72 6f 74 6f 72 72 61 63
65 63 61 72 49 70 72 65 66 65 72 70 69 6b 61
79 61 6b 6b

Do you know why?

Thanks
0
 
daskino12Author Commented:
Hello,

I am sorry but could you please explain to me what you did on the code?

    int QtyHex = 0;
     while (! fIn.eof() ) {
          fIn >> b;
          std::stringstream ss;
          ss << std::hex << (int)b;
          ReturnValue += ss.str() + " ";
          ++QtyHex;
          if (QtyHex == MaxHexNumbers)
          {
               ReturnValue += "\n";
               QtyHex = 0;
          }

Thanks

0
 
AxterCommented:
Try the following:

string openBinaryFile(const string &filename)
{
      ifstream fIn;
      string ReturnValue;
    fIn.open(filename.c_str(), ios_base::binary | ios_base::in );
      const int MaxHexNumbers = 15;
      int QtyHex = 0;
      while (! fIn.eof() ) {
            std::stringstream ss;
            ss << std::hex << (int)fIn.get();
            ReturnValue += ss.str() + " ";
            ++QtyHex;
            if (QtyHex == MaxHexNumbers)
            {
                  ReturnValue += "\n";
                  QtyHex = 0;
            }
      }
      return ReturnValue;
}

0
 
AxterCommented:
>>I am sorry but could you please explain to me what you did on the code?

That pretty generic question.
Can you post a specific question about the code.
Exactly what part of the code do you not understand?
0
 
DanRollinsCommented:
daskino12,

I don't get it.
The code I posted worked correctly (I tested it fully) and it did excatly what you wanted:  It reads a file and generates a string of text that was the input data but in hexidecimal representation.  Each byte is represented by two characters and they are separted by a single space.  After every 15th set, I have added a CRLF to delimit the end of line.

Did you even try my code?  If so, what's the problem?

-- Dan  
0
 
daskino12Author Commented:
Hello,

Like what does the code do in the following code:

ss << setfill('0') << setw(2) <<  std::hex << c;
          ss << " ";
          ++QtyHex;
          if (QtyHex == MaxHexNumbers)
          {
               ss << endl;
               QtyHex = 0;

And, yes, it works perfectly.

Thanks
0
 
daskino12Author Commented:
Hello Dan,

I am sorry but your code doesn't really fit into my project..like I can only write codes under the function "string openBinaryFile( string filename)."  However, your code did help me to get some ideas.  I am really sorry and thank you very much.
0
 
AxterCommented:
ss << setfill('0') << setw(2) <<  std::hex << c;

setfill tells the stream to fill in '0' if the input data is less then 2 characters.

setw(2) tells the stream to have a minimum width of 2 characters

ss << " ";// Add a space to the input stream

++QtyHex; //Use this variable to determine if 15 Hex numbers have been entered already
if (QtyHex == MaxHexNumbers) //If 15 Hex numbers have been added to input streeam, then send end line character and reset QtyHex to zero
0
 
daskino12Author Commented:
Hello,

Great.

Thanks a lot
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.