我可以在C ++中将指针地址(即十六进制整数)转换为十进制和八进制基数int [英] Can I convert a pointer address (i.e. an hex integer) to decimal and octal base int in C++

查看:481
本文介绍了我可以在C ++中将指针地址(即十六进制整数)转换为十进制和八进制基数int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

using namespace std;

int main()
{
    int *a = nullptr;
    int b;
    a = &b;

    cout << noshowbase;
    cin >> b;
    cout << dec << a << '\t' << oct << a << '\t' << hex << a;
}

请考虑以下代码.它旨在使用<iostream>流将十六进制整数(此处为&ba)的地址(此处为&ba)转换为decoct值.机械手..但是,在运行时,所有这些机械手的输出都是相同的(hexdecoct)..两者都没有任何编译错误.那么,您能详细说明一下原因吗?另外,noshowbase似乎对输出没有任何影响..在地址之前始终输出0x.

Consider this code.. It is designed to convert a variable's (here b) address (&b or a) which is a hex integer to dec and oct values using <iostream> stream manipulators.. But on running, the output is same for all of them(hex,dec,oct).. Neither, there is any compilation error. So can you please elaborate the reason for this?? Also the noshowbase does not seems to be having any effect on output.. 0x is output anyways before the address..

推荐答案

要解决您的主题,没有十六进制整数"之类的东西.有整数,可以将其格式化为十六进制,但是格式化不是整数的固有部分.

To address your topic, there is no such thing as a "hex integer". There are integers and they can be formatted as hex, but the formatting is not an intrinsic part of the integer.

现在,为什么总是将指针格式化为十六进制?原因是这就是它定义的工作方式.我也称此为方便,但这可能是因为我熟悉该格式,并且可以从中读取一些信息,甚至比从十进制输出中读取更好.格式化程序不更改此格式的原因是,指针不被视为整数.您还会发现指针算术的行为不像整数算术,在这种情况下,核心语言的行为就像IOstreams.

Now, why are pointers always formatted as hex? The reason is that that's the way it is defined to work. I'd also call this convenient, but that might be because I'm familiar with the format and can read some information from it even better than from decimal output. The reason this doesn't change with formatters is that a pointer is not considered an integer. You will also find that pointer arithmetic doesn't behave like integer arithmetic, which is a case where the core language behaves like IOstreams.

那么,如何获取您选择的格式?很简单,首先将指针转换为整数,然后可以使用选择的格式.为了做到这一点,我将使用size_t i = reinterpret_cast<size_t>(&b);.根据编译器的不同,我还将考虑使用uintptr_t而不是size_t,因为该类明确用于保存指针中的信息.

So, how to get the format of your choice? Simple, convert the pointer to an integer first, then you can use the formatting of your choice. In order to do that, I would use size_t i = reinterpret_cast<size_t>(&b);. Depending on the compiler, I would also consider using uintptr_t instead of size_t, because that one is explicitly intended to hold information from a pointer.

这篇关于我可以在C ++中将指针地址(即十六进制整数)转换为十进制和八进制基数int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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