1. 发现在u-boot中有些十六进制数,如0x30000000 0x00200000 不直观,搞个小程序直观的显示一下。
其中make_human_readable_str 是从 busybox-1.13.0/coreutils/ls.c拿过来的。
-
#include <stdio.h>
-
#include <stdlib.h>
-
typedef int smallint;
-
const char* make_human_readable_str(unsigned long long size, unsigned long block_size, unsigned long display_unit)
-
{
-
/* The code will adjust for additional (appended) units */
-
static const char unit_chars[]= { '\0', 'K', 'M', 'G', 'T', 'P', 'E' };
-
static const char fmt[] = "%llu";
-
static const char fmt_tenths[] = "%llu.%d%c";
-
-
static char str[21] ; /* Sufficient for 64 bit unsigned integers */
-
-
unsigned long long val;
-
int frac;
-
const char *u;
-
const char *f;
-
smallint no_tenths;
-
-
if (size == 0)
-
return "0";
-
-
/* If block_size is 0 then do not print tenths */
-
no_tenths = 0;
-
if (block_size == 0)
-
{
-
no_tenths = 1;
-
block_size = 1;
-
}
-
-
u = unit_chars;
-
val = size * block_size;
-
f = fmt;
-
frac = 0;
-
-
if (display_unit)
-
{
-
val += display_unit/2; /* Deal with rounding */
-
val /= display_unit; /* Don't combine with the line */
-
/* will just print it as ulonglong (below) */
-
}
-
else
-
{
-
while ((val >= 1024) && (u < unit_chars + sizeof(unit_chars) - 1))
-
{
-
f = fmt_tenths;
-
u++;
-
frac = (((int)(val % 1024)) * 10 + 1024/2) / 1024; //这句写得太牛了
-
val /= 1024;
-
}
-
if (frac >= 10)
-
{ /* We need to round up here. */
-
++val;
-
frac = 0;
-
}
-
/* Sample code to omit decimal point and tenths digit. */
-
if (no_tenths)
-
{
-
if (frac >= 5)
-
{
-
++val;
-
}
-
f = "%llu%*c" /* fmt_no_tenths */;
-
frac = 1;
-
}
-
}
-
-
/* If f==fmt then 'frac' and 'u' are ignored. */
-
snprintf(str, sizeof(str), f, val, frac, *u);
-
-
return str;
-
}
-
-
int str2num(char str[])
-
{
-
unsigned long n = 0;
-
int i;
-
for(i=0; str[i]!='\0'; i++)
-
{
-
if(str[i]>='0' && str[i]<='9')
-
n = n*16 + str[i] - '0';
-
if(str[i]>='a' && str[i]<='f')
-
n = n*16 + str[i] - 'a' + 10;
-
if(str[i]>='A' && str[i]<='F')
-
n = n*16 + str[i]- 'A' + 10;
-
}
-
return n;
-
}
-
-
int main(int argc, char *argv[])
-
{
-
unsigned long num = 0;
-
if( argc < 2)
-
{
-
printf("usage: %s \n", argv[0]);
-
return -1;
-
}
-
-
//支持输入'0x'打头的十六进制数
-
if(argv[1][0]=='0' && argv[1][1]=='x' || argv[1][1]=='X')
-
{
-
printf("Hex:%s\n", argv[1]);
-
num = str2num(&argv[1][2]);
-
}
-
else
-
{
-
printf("Hex:Ox%s\n", argv[1]);
-
num = str2num(argv[1]);
-
}
-
printf("Dec:%ld\n", num);
-
printf("readable: %s\n", make_human_readable_str(num,1,0));
-
return 0;
-
}
实验一下:
root@ubuntu:~/test# ./test 0x30000000
Hex:0x30000000
Dec:805306368
readable: 768.0M
还不错,呵呵。
阅读(3576) | 评论(0) | 转发(0) |