Question

hex + Ascii display problem

Asked by: MellowD0c

I have run into a situation where i cannot figure out a way to display Hex with text on right site of that particular hex(by reading from file char by char and converting it to hex and displaying it). The following code only allows me to display hex with 16 chars on line, as for hex requirement that is good, but at the end of line i want to display text of that 16 chars of hex as well. How can i do it? Some code will help and if possible plz try to adjust it in the following code.


.....main........    
     while (f)
     {
          int n = 16;
          for (int i =0; i<n; i++)
          {
                  f.get(c); //get text from file
               hexed(c); //convert to hex
                         
          }
          cout << endl;
     }
                   
     return (0);
}//main ends here


void hexed(char c)
{
     char LoNibble, HiNibble, LoChar, HiChar;
     char HexTab[]= "0123456789ABCDEF";
                                        LoNibble = c & 0x0F;
     HiNibble = (c >>4) & 0x0F;
     LoChar = HexTab[ LoNibble ];
     HiChar = HexTab[ HiNibble ];
     cout << HiChar << LoChar  << " " ;
}

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-01-21 at 06:47:10ID20468144
Tags

hex

,

lochar

Topic

C++ Programming Language

Participating Experts
4
Points
45
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Hex => ASCII
    How can I convert Hex data to ASCII data?
  2. Hex to Ascii/Integer
    (C on Solaris 2.x) Hi, I'm having problems on how to store some Hex values. Hopefully you can help this newbie in C. First of all, here're 2 simple variables I'm having ... unsigned char *source, *dest; After I read in a string e.g. "12AB" into source, I co...
  3. decimal to hex
    how to convert decimal to hex in c language?
  4. CString --> Hex
    hi im looking for a way to convert a CString to a Hex (ex. This is a test = 54 68 69 73 20 69 73 20 61 20 74 65 73 74) im useing VC++ 6 sp 5 iv used string.Format("%02X",hex); but dont know what the 02 dose and dosent work.... gives the same thing for every letter i...
  5. Anything in C/C++ to convert Decimal to Hex
    Anything in C/C++ to convert Decimal to Hex..? ~Rajesh

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jkrPosted on 2003-01-21 at 06:56:13ID: 7770744

Try

    while (f)
    {
         int n = 16;
         // array to store the line
         char acText [ 16 + 1]; // plus trailing '0'
         memset ( acText, 0, sizeof ( acText));

         for (int i =0; i<n; i++)
         {
              f.get(c); //get text from file
              acText [ i] = c;
              hexed(c); //convert to hex
                       
         }
         cout << acText << endl;
    }

 

by: MellowD0cPosted on 2003-01-21 at 07:48:32ID: 7771211

thanks one addition i want on that is if it was possible to print out number of lines as well on left side before hex (in hex format)  starting from 0? Also what does memset do? I have raised 10 more points...

 

by: jkrPosted on 2003-01-21 at 07:56:41ID: 7771304

>>if it was possible to print out number of lines as well on left side before hex

Sure:

   while (f)
   {
        unsigned int nLines = 1;

        int n = 16;
        // array to store the line
        char acText [ 16 + 1]; // plus trailing '0'
        memset ( acText, 0, sizeof ( acText));

        cout << setbase ( ios_base::hex) << nLines << " ";
        for (int i =0; i<n; i++)
        {
             f.get(c); //get text from file
             acText [ i] = c;
             hexed(c); //convert to hex
                       
        }
        cout << acText << endl;

        nLines++;
   }


>>Also what does memset do?

'memset()' initializes the char array with bin. zeros.

 

by: jkrPosted on 2003-01-21 at 07:57:55ID: 7771318

BTW, 'setbase ( ios_base::hex)' might actually help you to get rid of the 'hexed()' function by using

cout << setbase ( ios_base::hex) << (int) c;

 

by: MellowD0cPosted on 2003-01-21 at 08:03:19ID: 7771360

no i cannot use iso_base::hex or any such manipulators :( for conversion purposes

 

by: jkrPosted on 2003-01-21 at 08:10:08ID: 7771426

Well, then we could use

char acLine [ 10];
sprintf ( acLine, "0x%4.4x ", nLines); // change '4' to the witdh you actually want to use

cout << acLines;

 

by: MellowD0cPosted on 2003-01-21 at 08:17:19ID: 7771480

if i try to output line numbers with the function you gave to output lines in hex (I made my original hex function to work with it to ouput lines in hex format) with numbers incrementing till eOf. It puts just 1 before each line and doesnt increment with lines..  

while (f)
           {
       unsigned int nLines = 1;

       int n = 16;
       // array to store the line
       char acText [ 16 + 1]; // plus trailing '0'
       memset ( acText, 0, sizeof ( acText));

       inthexed( nLines);
       for (int i =0; i<n; i++)
       {
            f.get(c); //get text from file
            acText [ i] = c;
            hexed(c); //convert to hex
                     
       }
       cout << acText << endl;

       nLines++;
  }

//my original char to hex converter that i used to convert number of lines from decimal to hex

void inthexed(unsigned int c) //char c to un..int c
{
     int LoNibble, HiNibble, LoChar, HiChar; //changed from char to int
     char HexTab[]= "0123456789ABCDEF";
     LoNibble = c & 0x0F;
     HiNibble = (c >>4) & 0x0F;
     LoChar = HexTab[ LoNibble ];
     HiChar = HexTab[ HiNibble ];
cout << HiChar << LoChar  << " " ;
}


what i want number output to be like is in 00000000 (for 0) and .........(000000A0) for 10 and so on format...

 

by: jkrPosted on 2003-01-21 at 08:47:52ID: 7771767

Well, then use


while (f) {

      unsigned int nLines = 1;

      int n = 16;
      // array to store the line
      char acText [ 16 + 1]; // plus trailing '0'
      memset ( acText, 0, sizeof ( acText));

      char acLine [ 10];
      sprintf ( acLine, "%8.8x ", nLines++);
      cout << acLines;
      for (int i =0; i<n; i++)
      {
           f.get(c); //get text from file
           acText [ i] = c;
           hexed(c); //convert to hex
                     
      }
      cout << acText << endl;
 }

I am not gonna change your 'handrolled' function to do the formatting :o)

 

by: SaltePosted on 2003-01-21 at 09:25:51ID: 7772121

Just a little point.

When you want to display the text of the 16 bytes you should probably make sure that 'undisplayable' characters and characters that do things to cursor aren't simply printed out, make sure you replace those with a dot or space or something before you print the text.

This function does a hex display of 16 bytes at a time:

void hexline(unsigned int addr,
             const unsigned char * buf, int n,
             ostream & os)
{
   // addr is the address to display at start.
   // buf is a pointer to data, n is number of bytes in
   // data (usually 16 but can be less on the last
   // record.
   // os is the output stream.
   char abuf[16 + 1]; // buffer for the text.

   char tmp[4 + 1]; // address buffer 4 digits + null.

   sprintf( tmp, "%04x", addr);
   os << tmp << ':';

   static const char digits[17] = "0123456789abcdef";

   for (int i = 0; i < n; i++) {
       unsigned char uc = buf[i];

       if (i == 8)
          os << " -"; // output a dash in the middle.

       os << ' ' << digits[uc >> 4] << digits[uc & 0x0f];
       if (is_special(uc))
         uc = '.'; // replace uc with . if special.
       abuf[i] = static_cast<char>(uc);
   }
   abuf[n] = '\0';

   // if n < 16 we must add blanks to make the text buf
   // align with previous lines.
   while (n < 16) {
      if (n == 8)
         os << "  "; // use " -" if you want to.
      os << "   ";
      ++n;
   }
   os << ' ' << abuf << endl;
}

memset(dst,val,count); does the same as:

for (int i = 0; i < count; i++) {
   static_cast<char *>(dst)[i] = val;
}

only more efficient.

You can use memset to clear a buffer or set a portion of the buffer equal to blanks. Since I had my function do output to ostream I didn't need to use memset but if you want to output to a string instead you can use memset to blank out all the blanks as I did in that while loop.


The function written above can be called like this:

unsigned int addr = 0;
int n;
unsigned char buf[16];

while ((n = fread(buf,16,1,fp)) > 0) {
   hexline(addr,buf,n,cout);
   addr += n;
}

and the file will output in the 'usual' hexdump fashion.

<line> 0000 00 11 22 33 44 55 66 77 - 88 99 aa bb cc dd ee ff .."3DUfw........<line end>

The text may vary depending on your coding system for upper bytes in the range 0x80-0xff.

Alf

 

by: MellowD0cPosted on 2003-01-21 at 12:31:48ID: 7773758

Thanks guys i will see if i could split up points and hand them to you both since what both of you did was of great help.

 

by: MellowD0cPosted on 2003-01-21 at 12:41:56ID: 7773853

Thanks guys i will see if i could split up points and hand them to you both since what both of you did was of great help.

 

by: moduloPosted on 2003-01-21 at 13:01:45ID: 7774038

Dear MellowD0c

I've refunded 45 points to enable you to accept the comment for one expert and to post a
"Points for <expertname>" Q for the other expert in the same topic area.

Please:
1) Post the link to the original Q in the "Points for <expertname>" and
2) Add in the original Q a comment with the link to the "Points for <expertname>", thus the email notif will warn the expert.

modulo

Community Support Moderator
Experts Exchange

 

by: MellowD0cPosted on 2003-01-21 at 13:30:06ID: 7774296

 

by: 171160Posted on 2004-05-09 at 05:50:52ID: 11025519


Please can you help me convert to following code base_10_value to base_16_value.  I had been trying very hard bu I have been unsuccessful.  I would appreciated your help very much.  Thank you.  The program must add two very large hexadecima (unsigned) integers.  The two summads should be stored arrays. Starting at the least significant digits, the program should compute the sum by adding  the two integers digit by digit.  

My luck,

 

by: 171160Posted on 2004-05-09 at 05:59:13ID: 11025539



Please can you help me convert to following code base_10_value to base_16_value.  I had been trying very hard bu I have been unsuccessful.  I would appreciated your help very much.  Thank you.  The program must add two very large hexadecima (unsigned) integers.  The two summads should be stored arrays. Starting at the least significant digits, the program should compute the sum by adding  the two integers digit by digit.  

My luck, #include<iostream.h>



const char ch='A', 'B', 'C', 'D', 'E', 'F';


void main(){



      char first_summand[256];
      char second_summand[256];
      char sum[258];
      char ch=isum;
      char ch=icarry;
      int isum, icarry;
      char ch * first, * second, * csum;
      

      //Input the first summand
      cout << "Input the first summand:(1-9,A-F(UPPERCASE LETTERS)) ";
      first = first_summand;
      *first++ = '\0';
      while ( (*first++ = cin.get() )!= '\n' )
            ;

      *--first = '\0';
      first--;

      //Input the second summand
      cout << "Input the second summand:(1-9,A-F(UPPERCASE LETTERS))";
      second = second_summand;
      *second++ = '\0';
      while ( (*second++ = cin.get()) != '\n')
            ;

      *--second = '\0';
      second--;


      //Calculate the sum
      csum = sum + 256;
      *csum-- = '\0';
      icarry = 0;

      while ( *first || *second) {
            if ( *first && *second) {
                  isum = *first-- + *second-- - 2 * int('0') + icarry;
                  icarry = isum / 16;
                  isum = isum % 16;
                  *csum-- = isum + '0';

            }

            if ( *first && (! *second) ) {
                  isum = *first-- - int ('0') + icarry;
                  icarry = isum / 16;
                  isum = isum % 16;
                  *csum-- = isum + '0';

            }
            if ( (! *first) && *second) {
                  isum = *second-- - int('0') + icarry;
                  icarry = isum / 16;
                  isum = isum % 16;
                  *csum-- = isum + '0';
            }


      }
      char ch = *csum;

      if ( icarry ) {
            *csum-- = icarry + '0';
      }
      csum++; // adjust csum to point to the start of the output string
      cout << (csum) << '\n';
      }

 

by: SaltePosted on 2004-05-10 at 07:28:52ID: 11031430

One,

If you have a question of code like this, you should post a new question.

Even if it is related to the old already answered question - since you have a new question,
you really should point a question.

If you don't plan to award anyone anything for helping you, why should we help ya?

Oh well, I am a nice guy so I might help you if I get the time :-)

For one thing, it might be homework so I cannot give you solution. However, you did post a program and I can comment on that one :-)

Secondly, your problem description appear to indicate multiple precision and you might try to read some info on the net on how multiple precision numbers works. Adding in particular is very easy to do.

Anyway, here are some comments on the program code you gave.

onst char ch='A', 'B', 'C', 'D', 'E', 'F';

What is this? In C the comma operator is an operator that says "discard whatever result you computed before comma and only use the expression after the comma".

Thus ch gets the value 'F' and all the other A, B etc are ignored.

I don't think that is what you intended so you should probably rethink this statement.

Secondly, the way you read the numbers are "hairy" for lack of a better word and most
likely wrong. Again I think you should rethink what it is you intend to do and ask yourself if this statement really does what you want it to do.

You say you want the numbers with the least significant digit at the smaller index. Thus
you should read the digit you read first - the most significant digit - at the END of the buffer.

So something like:

char buf[256];

char * end = buf + sizeof(buf); // end point to end of buf.
char * ptr = end; // ptr points to end of buf.

add in the digits as you read them by *--ptr = .....,

You should probably also convert the characters to hex digits - nibbles. A quick and easy
way to do that is like this:

static const char digits[] = "0123456789abcdefABCDEF";

if c is a char that you just read the next digit, you do:

char c = cin.get();
char * p = strchr)digits, c);
if (p != NULL) { // valid digit.
   int x = p - digits;
   // The following statement makes the digit value become 11 if you read 'B' which
   // in the array above gets index 17.
   if (x >= 16)
       x -= 6;
   *--ptr = static_cast;char>(x);
}

You can then translate this to a loop so you read all the digits.

The number is then stored in the array pointed to by ptr and of length end - ptr and the least
significant digit is at ptr[0], the next least significant is at ptr[1] and the most significant digit
is at ptr[end - ptr - 1} etc.

Also, I STRONGLY suggest you put the "read a number into the array" in a separate function and call that function twice - once for each number - instead of having two almost identical loops. What you do above there is very bad style.

If you keep the numbers as text strings, then your addition is almost correct. The only problem is that you forget to store away isum anywhere, you compute it correctly and then promptly throws it away and ignore it.

If you do change the input routine to produce nibbles as I suggested above, remember to remove the -2 * int('0') above. If you do keep it as text you MUST include it. Also remember to add '0' back to isum before storing it in result. You do not need to cast the '0' to int. C++ has 'x' as a char type but it is automatically converted to int when you try to add it to something that doesn't fit in a char. A char can always be stored in an int without any explicit casting, so '0' is just as fine as int('0') there.

I believe the two if statements inside the while loop is to handle the case that one of the numbers are shorter than the other.

For one thing this is very inefficient since you do the test for both in the while loop each time. Once any of those tests are true you don't have to do the big loop any more and just add in the carry etc. Another way to handle this is simply to have each digit be '0' whenever you reach the end of the string before the other string is empty. Something like this:

isum = 0;
isum += *first ? *first : '0';
isum += *second ? *second : '0';
isum += icarry - 2 * '0';
icarry = isum >> 4; // same as isum / 16.
isum &= 15; // same as isum %= 16

should get you a valid isum as a value in the range 0-15, if you want it to be a digit
you can then use the digits[] array and index into it.

Hope this is of help.

Alf

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...