首页 > 代码库 > C++学习笔记:不用sizeof判断int类型占用几个字节

C++学习笔记:不用sizeof判断int类型占用几个字节

#include <stdio.h>
#include <string.h>

char *change(int val, int base, char *retbuf)
{
    static const char *str = "0123456789ABCDEF";
    char *p;
    char buf[15];

    p = buf+14;
    *p = 0;

    do { *--p = str[val % base]; } while( val /= base );
    strcpy(retbuf,p);
    return retbuf;
}

int main()
{

     int i = 1;

     char binbuf[32];
     printf("%s  %d\n", change(i, 2, binbuf), i);

     int sum = 0;
     while(0 != i)
     {
          sum++;
          i = i<<1;
          printf("%s  %d\n", change(i, 2, binbuf), i);
     }
    
     printf("sum = %d\n", sum);

}