小端字节序 : 高字节序存于内存的高地址;低字节序存于内存的低地址。
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, size_t len) {
size_t 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)ival;
int *pval=&ival;
show_int(ival);
show_float(fval);
show_pointer(pval);
int num = 1;
if (ival&num == 1)
printf("学号20165230的笔记本电脑是小端\n");
else
printf("学号20165230的笔记本电脑是大端\n");
}
void main() {
int val;
scanf("%d", &val);
test_show_bytes(val);
}
调用附图代码,编写一个程序 “week0202学号.c",用show_int(), show_float()打印一下你的4位学号,参考教材P33打印出匹配的位序列。
提交运行结果截图,要全屏,要包含自己的学号信息
参考教材p82,给出出匹配的位序列的推导过程
int i, j;
for(i=0; i<11; i++)
printf(" ");
for(i=0; i<len; i++){
for(j=0; j<8; j++){
printf("%d", (start[i]>>j) & 0x1);
}
}
printf("\n");
IEEE浮点表示
代码
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, size_t len) {
size_t i;
for(i=0; i<len; i++)
printf(" %.2x", start[i]);
printf("\n");
}
void show_int(int x) {
size_t len=sizeof(int);
show_bytes((byte_pointer) &x, len);
byte_pointer start=(byte_pointer) &x;
int i, j;
for(i=0; i<11; i++)
printf(" ");
for(i=0; i<len; i++){
for(j=0; j<8; j++){
printf("%d", (start[i]>>j) & 0x1);
}
}
printf("\n");
}
void show_float(float x) {
size_t len=sizeof(float);
show_bytes((byte_pointer) &x, len);
byte_pointer start=(byte_pointer) &x;
int i, j;
for(i=0; i<len; i++){
for(j=0; j<8; j++){
printf("%d", (start[i]>>j) & 0x1);
}
}
printf("\n");
}
void show_pointer(void *x) {
show_bytes((byte_pointer) &x, sizeof(void *));
}
void test_show_bytes(int val) {
int ival=val;
float fval=(float)ival;
int *pval=&ival;
show_int(ival);
int i;
for(i=0;i<11;i++){
printf(" ");
}
for(i=0;i<13;i++)
printf("*");
printf("\n");
show_float(fval);
}
void main() {
int val;
scanf("%d", &val);
test_show_bytes(val);
}
short int v = -学号后四位
unsigned short uv = (unsigned short) v
printf("v = %d, uv = %u\n ", v, uv);
在第三行设置断点用gdb调试,用p /x v; p /x uv 查看变量的值,提交调试结果截图,要全屏,要包含自己的学号信息
分析p /x v; p /x uv 与程序运行结果的不同和联系
#include<stdio.h>
void main()
{
short int v = -5230;
unsigned short uv = (unsigned short) v;
printf("v = %d, uv = %u\n ", v, uv);
}
数值可能会改变,但是位模式不变
原文:https://www.cnblogs.com/tiankunye/p/9800433.html