ascii to hex

Hello guys,

i want to convert a text file to hex and have written this code :

int main(int argc, char **argv)
{
            ifstream file;
            string fileName = "CODEZ";
     
            file.open(fileName.c_str()); //  oeffen im Text-Modus
            if(file)
            {
                        string text; // Haupttext
                        while(!file.eof())
                        {
                                    char buffer; // Buffer
                                    file.get(buffer);
                                    //text += buffer; // Zeichen zusammensetzen
                                    cout << "%" << hex <<(int)buffer  ;
                        }
                          file.close();
            }
            else
            {
                        cout << "Datei Fehler!";
            }
            cin.get();
            return 0;
}

My problem is to recognise where the line of the original document ends.
The input from text file is :

hello
world

The output is :

%68%65%6c%6c%6f%a%77%6f%72%6c%64%a%a

But my desired Output is:

%68%65%6c%6c%6f%a
%77%6f%72%6c%64%a

The Strings in the text file are of various length,...but in each line is just one word!
Any ideas how to solve this problem?

My bad, I solved the problem before looking to see that you did not post this in the general unix area. But, since I went to the trouble...

cat infile.txt | od -An -t dC | tr -d "\n" | sed 's/ 10 / 10~ /g' | tr "~" "\n"

will take an input file, and provide all the hexadecimal representations of each character, putting output out on separate lines (for separate input lines).

cat infile.txt | od -An -t dC | tr -d "\n" | sed 's/ 10 / 10~ /g' | tr "~" "\n"

will take an input file, and provide all the hexadecimal representations of each character, putting output out on separate lines (for separate input lines).
[/quote]

Thank your for your suggestion. But the code you provided generates a output like this :

104  101  108  108  111   10
119  111  114  108  100   10

But i need the strings in the above mentioned format like :

%68%65%6c%6c%6f%a
%77%6f%72%6c%64%a

Later on i want to feed a Java-Script with the output.
When i use the unescape() command i want to have the plain text again.

OK, it is ugly, but...

cat infile | od -An -t x2 | tr " " "\n" | tr -s "\n" | awk '{print "%"substr($1,1,2);print "%"substr($1,3,2)}' | sed 's/0a/0a~/g' | tr -d "\n" | tr "~" "\n"

What about:

$ cat file
hello
world
$ od -An -t x1 file| awk '{gsub("0a","0a%\n");gsub(" ","%")}{printf("%s", $0)}'
%68%65%6c%6c%6f%0a%
%77%6f%72%6c%64%0a%

thx a lot Franklin, this is exactly what i needed :slight_smile: