Saturday, October 19, 2013

hex and octal and the cout stream

Use 0x in front of a number to put in hex and just 0 for octal. I can imagine a lot of bugs appear just using octal on things like string conversions etc!

The default for the cout stream is to assume that all feeds into the stream are in decimal, however you can change the number base through feeding a "hex" or "oct" to the stream - e.g. cout << hex << 42. hex (and oct?) are both part of the std namespace.

NOTE if you use a constant in a program - e.g. cout << "year = " << 1492 << endl; - then the 1492 would be stored as an int unless there was a reason not to do so (e.g. if the value is too large or you specify otherwise using some special suffixes).

You can place letters at the end of a numeric constant to specify the type - e.g. 22022LU or 22022UL - both unsigned long; use LL for long long etc.

#include <iostream>

using namespace std;

int main()
{
  int chest = 42; //decimal integer
  int waist = 0x42; //hexadecimal integer
  int inseam = 042; //octal integer

  cout << "monsiuer cuts a striking figure" << endl;
  cout << "chest = " << chest << " 42 in decimal" << endl;
  cout << "waist = " << waist << " 0x42 in hex" << endl;
  cout << "inseam = " << inseam << " 042 in octal" << endl;
    return 0;
}

No comments:

Post a Comment