0

I understand that integers are stored in binary notation, but I was wondering how this affects the reading of them - for example:

Assuming

cin.unsetf(ios::dec); cin.unsetf(ios::hex); and cin.unsetf(ios::oct);

the user inputs

0x43 0123 65

which are stored as integers. Now assume that the program wants to recognize these values as hex, oct, or dec and does something like this.

void number_sys(int num, string& s)
{
string number;
stringstream out;
out << num;
number = out.str();
if(number[0] == '0' && (number[1] != 'x' && number[1] != 'X')) s = "octal";
else if(number[0] == '0' && (number[1] == 'x' || number[1] == 'X')) s = "hexadecimal";
else s = "decimal";
}

the function will read all of the integers as decimal. I put in some test code after the string conversion to output the string, and the string is the number in decimal form. I was wondering if there is a way for integers to keep their base notation.

Of course you could input the numbers as strings and test that way, but then there is the problem of reading the string back as an int.

For example:

       string a = 0x43;
       int num = atoi(a.c_str());
       cout << num; // will output 43

It seems like keeping/converting base notation can get very tricky. As an added problem, the hex, dec, and oct manipulators wouldn't even help with the issue shown above since the integer is being stored completely incorrectly, it's not even converting to a decimal.

trikker
  • 2,651
  • 10
  • 41
  • 57

1 Answers1

5

Integers (and all other data) are not stored using "binary notation", they are stored as binary numbers. And no, there is no way for integers to retain their input format (which is what you are actually asking).

  • Isn't being stored using binary notation the same thing as saying that they are stored as binary numbers. – trikker Jul 28 '09 at 17:59
  • No. Notation refers to some written, human-readable form. Computer data is stored in an unwritten form, as charges in transistors (or similar). –  Jul 28 '09 at 18:02
  • It's a question of emphasis: they're stored as numbers. Actual computers do use binary internally, and there are various operators on integers which are defined in terms of how they affect the binary digits of the number. However, numbers don't have a base, they aren't binary or decimal or octal or hex, they just have a value. 0xF and 15 aren't different numbers, they're different strings representing the same number. Once those two strings are converted to int they are completely indistinguishable. – Steve Jessop Jul 28 '09 at 18:05
  • Although fair enough, if Neil wants to say that "notation" implies "human readable" then I'm not going to have an argument about the English language :-) – Steve Jessop Jul 28 '09 at 18:07