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

来源:互联网 发布:蜘蛛侠淘宝客 编辑:程序博客网 时间:2024/06/05 13:26

  • showbytes
    • 代码总览
    • 代码说明
    • 编译与结果显示

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位机的输出结果
3930000000e44046987de0a9fe7f0000

解释:

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

原创粉丝点击