您的位置:首页 > 移动开发

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

2017-10-26 01:11 441 查看
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位机的输出结果

39300000
00e44046
987de0a9fe7f0000


解释:

123456的16进制表示为 0x00003039,由于linux 64位采用小端存储,所以先输出低位39,然后再输出30。所以结果如上述表示。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cs-app c