基础编程面试 (2)

1、计算一个字节内有多少bit被置为1?

 1 #include <stdio.h>
 2 
 3 #define BIT7 (0x1<<7)  //0x1000 0000
 4 
 5 int calculate(unsigned char c)
 6 {
 7     int count = 0;
 8     int i;
 9     unsigned char b = BIT7;
10 
11         for(i=0;i<sizeof(c)*8;i++)
12         {
13             if((c&b) == b)
14             {
15                 count++;
16             }
17             b = b>>1;
18         }
19         return count;
20 }
21 
22 int main()
23 {
24     unsigned char c = 0;
25     int count = 0;
26 
27     printf("c=");
28     scanf("%d",&c);
29 
30     count = calculate(c);
31     printf("count = %d
",count);
32     return 0;
33 }
setbit.c

2、判断处理器是大端模式还是小端模式?

 1 #include <stdio.h>
 2 
 3 int main(int argc, const char *argv[])
 4 {
 5     int  i = 1;
 6     int *p = &i;
 7     
 8     if(*p == i)
 9     {
10         printf("Little endian
");
11     }
12     else
13     {
14         printf("Big endian");
15     }
16     return 0;
17 }
Little_Big.c

将00 00 00 01放入计算机

Little-endian :  低地址: 0x4000 --- 01 00 00 00 --- 0x4001: 高地址    (低位字节存在低地址,高位字节存在高地址)

Big-endian    : 低地址: 0x4000 --- 00 00 00 01 --- 0x4001: 高地址    (低位字节存在高地址,高位字节存在低地址)

一般从低地址开始读取数据,

取出i的地址,存入,若为小端模式,存入后读到的地址与实际的地址是相同的,都是从低地址开始读地址与取数据

原文地址:https://www.cnblogs.com/y4247464/p/12692361.html