整数存储 - 十六进制/八进制 [英] Integer storage - Hexadecimal/Octal

查看:154
本文介绍了整数存储 - 十六进制/八进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道整数以二进制符号存储,但我想知道这将如何影响它们的读取 - 例如:

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

假设

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

用户输入

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.

当然,你可以输入数字作为字符串,然后测试这种方式,但是有将字符串读取为int的问题。

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.

例如:

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

看起来像保留/转换基本符号可能会非常棘手。作为一个附加的问题,hex,dec和oct操纵器甚至不会帮助上面显示的问题,因为整数存储完全不正确,甚至不会转换为小数。

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.

推荐答案

整数(和所有其他数据)不是使用二进制符号存储,它们存储为二进制数。没有,整数不能保留他们的输入格式(这是你实际要求的)。

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).

这篇关于整数存储 - 十六进制/八进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆