如何在c中打印内存位 [英] how to print memory bits in c

查看:20
本文介绍了如何在c中打印内存位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在内存中表示数字.我想知道如何在某些 int 和 float 变量的内存中打印实际表示(二进制或十六进制).

I'm learning how numbers are represented in memory. I want to know how to print the actual representation (binary or hexadecimal) in memory of some int and float variables.

例如,我想看看当这些数字相加或相减会导致溢出时会发生什么.

I'd like to see what happens with that numbers when adding or subtracting it causes overflow, for example.

如何访问内存并打印它?

How can I access memory and print it?

推荐答案

您需要将指向相关变量的指针分配给 char *,并将其视为字节数组长度 sizeof(variable).然后,您可以使用 %X 格式说明符将每个字节以十六进制打印到 printf.

You would need to assign a pointer to the variable in question to a char *, and treat it as an array of bytes of length sizeof(variable). Then you can print each byte in hex using the %X format specifier to printf.

你可以像这样定义一个函数:

You can define a function like this:

void print_bytes(void *ptr, int size) 
{
    unsigned char *p = ptr;
    int i;
    for (i=0; i<size; i++) {
        printf("%02hhX ", p[i]);
    }
    printf("
");
}

然后这样称呼它:

int x = 123456;
double y = 3.14;
print_bytes(&x, sizeof(x));
print_bytes(&y, sizeof(y));

这篇关于如何在c中打印内存位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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