打印十六进制数作为十进制

时间:2011-10-06 13:01:55

标签: c linux terminal

我正在尝试在Linux中制作fdisk程序。我有一个缓冲区,其中包含分区磁盘信息(起始扇区结束扇区 - 分区大小等)。

我有缓冲区数组char buf[512]和缓冲区包含所需信息的问题,我想用十进制打印它。结果应为dec 2048,但我的程序会打印hex 0800

该程序可以看到每个数字八零零,我希望它看到八百。


守则

#define _LARGEFILE64_SOURCE
#define buff_SIZE 512

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>


int main(int argc, char ** argv){


  int fd; // File descriptor
  unsigned char buf[buff_SIZE];

  if(argc<2) {
     perror("Error: No such file or directory");
     exit(2); // File scripted: 0 input 1 output 2 error
  }

  // Open Driver::
  if((fd=open(argv[1], O_RDONLY | O_LARGEFILE ))==-1){
     perror("Error: Can not open the file");
     exit(2);
  }

  // Reading file descriptor into buffer::
  if(read(fd, buf, buff_SIZE)!=buff_SIZE)
    perror("Error: Reading error");

  if ((buf[446]==0x80)||(buf[446]==0x00))
     printf("%x\n",buf[446]);
  int i;
  for(i=447;i<=449;i++)
    printf("%x\n",buf[i]);
  printf("Partation ID:%x\n",buf[450]);
  printf("Starting Sector:%x%x%x%x\n",buf[454],buf[455],buf[456],buf[457]); //***THE PROBLEM***

 close(fd);
 return 0;}

输出

80
20
21
0
Partation ID:83
Starting Sector:0800

这在六进制800h我需要它在十进制2048

1 个答案:

答案 0 :(得分:1)

printf("Starting Sector:%lu\n",
         (unsigned long)buf[454] * 0x1000
       + (unsigned long)buf[455] * 0x100
       + (unsigned long)buf[456] * 0x10
       + (unsigned long)buf[457] * 0x1);