Solved

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

Posted on 2003-10-22
30
517 Views
Last Modified: 2010-04-01
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
0
Comment
Question by:daskino12
  • 14
  • 11
  • 3
  • +2
30 Comments
 
LVL 15

Expert Comment

by:dualsoul
ID: 9605380
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
 
LVL 4

Expert Comment

by:havman56
ID: 9605939
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
 

Author Comment

by:daskino12
ID: 9607098
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
 

Author Comment

by:daskino12
ID: 9607116
Hello,

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

THanks

0
 
LVL 49

Assisted Solution

by:DanRollins
DanRollins earned 150 total points
ID: 9609071
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
 
LVL 49

Expert Comment

by:DanRollins
ID: 9609083
Correction: I forgot to add
    fIn.close();
before the return in the FileToHexString() fn.
-- Dan
0
 

Author Comment

by:daskino12
ID: 9609928
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
 
LVL 30

Expert Comment

by:Axter
ID: 9610623
Here's a modified version of Dan's code.
0
 
LVL 30

Expert Comment

by:Axter
ID: 9610625
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
 
LVL 30

Expert Comment

by:Axter
ID: 9610651
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
 

Author Comment

by:daskino12
ID: 9610819
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
 

Author Comment

by:daskino12
ID: 9610827
Hello,

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

Thanks
0
 

Author Comment

by:daskino12
ID: 9610922
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
 
LVL 30

Expert Comment

by:Axter
ID: 9611137
>>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
 
LVL 30

Expert Comment

by:Axter
ID: 9611139
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:daskino12
ID: 9611158
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
 

Author Comment

by:daskino12
ID: 9611170
Hello,

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

Thanks
0
 
LVL 30

Expert Comment

by:Axter
ID: 9611193
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
 

Author Comment

by:daskino12
ID: 9611200
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
 
LVL 30

Expert Comment

by:Axter
ID: 9611224
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
 

Author Comment

by:daskino12
ID: 9611237
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
 

Author Comment

by:daskino12
ID: 9611263
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
 
LVL 30

Expert Comment

by:Axter
ID: 9611269
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
 
LVL 30

Accepted Solution

by:
Axter earned 350 total points
ID: 9611362
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
 
LVL 30

Expert Comment

by:Axter
ID: 9611373
>>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
 
LVL 49

Expert Comment

by:DanRollins
ID: 9611469
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
 

Author Comment

by:daskino12
ID: 9611472
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
 

Author Comment

by:daskino12
ID: 9611498
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
 
LVL 30

Expert Comment

by:Axter
ID: 9611522
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
 

Author Comment

by:daskino12
ID: 9611539
Hello,

Great.

Thanks a lot
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now