cs:app学习笔记(1):show-bytes

show—bytes

代码总览

#include <stdio.h>
typedef unsigned char* byte_pointer;

void show_bytes(byte_pointer start, int len){
    int i;
    for (i = 0; i < len; i++)
        printf ("%.2x", start[i]);
    printf("\n");
}

void show_int(int x){
    show_bytes((byte_pointer)&x, sizeof (int));
}

void show_float(float x){
    show_bytes((byte_pointer)&x, sizeof (float));
}

void show_pointer(void *x){
    show_bytes((byte_pointer)&x, sizeof (void *));
}

void test_show_bytes(int val){
    int ival = val;
    float fval = (float) val;
    int *pval = &ival;
    show_int(ival);
    show_float(fval);
    show_pointer(pval);
}

int main(int argc, char const *argv[])
{
    int test = 12345;
    test_show_bytes(test);
}

代码说明

typedef unsigned char* byte_pointer;
  • unsigned char*命名为byte_pointer
  • 在cs:app中,提供的代码格式是如下:
typedef unsigned char *byte_pointer;
  • 虽然对于程序不影响,但是我更喜欢我的写法,这样更像指向无符号字符型的指针。
void show_bytes(byte_pointer start, int len){
    int i;
    for (i = 0; i < len; i++)
        printf ("%.2x", start[i]);
    printf("\n");
}
  • show-bytes 这个函数将传入无符号字符对象的指针,和该对象的字节数,然后通过在for循环中,使用printf ("%.2x", start[i]); 进行格式化输出。%.2x确保整数都以两位16进制数输出。
  • start代表对象的首地址,start[i] 代表从start[0] 开始第i个位置处的字节。
void show_int(int x){
    show_bytes((byte_pointer)&x, sizeof (int));
}

void show_float(float x){
    show_bytes((byte_pointer)&x, sizeof (float));
}

void show_pointer(void *x){
    show_bytes((byte_pointer)&x, sizeof (void *));
}
  • 这三个函数,将不同类型的对象的指针都强制转化成unsigned char* 类型,并用sizeof 关键字表示该数据所用字节数。
void test_show_bytes(int val){
    int ival = val;
    float fval = (float) val;
    int *pval = &ival;
    show_int(ival);
    show_float(fval);
    show_pointer(pval);
}

int main(int argc, char const *argv[])
{
    int test = 12345;
    test_show_bytes(test);
}
  • 主函数与测试函数。

编译与结果显示

  • 编译命令
gcc show-bytes.c -o main
./main
  • 在linux 64位机的输出结果
39300000
00e44046
987de0a9fe7f0000

解释:

123456的16进制表示为 0x00003039,由于linux 64位采用小端存储,所以先输出低位39,然后再输出30。所以结果如上述表示。

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值