-1

嘿伙计们,我的任务基本上是从 char 中获取小数。例如,输入参数是 8751。如何将 51(仅)转换为十进制?我知道如何获得 87,如果它是十六进制(0x8751 和 0xff),我也知道如何获得 51。

所以我的程序的输出是:

(0x87 & 0x7f)*128 + (0x51)

或者

(135-128)*128 + 81

谢谢

代码::

#include <iostream>
#include <cstdio>


int
main(int argc, char* argv[])
{
char* nums;
// long sum = 0;
 for ( int i = 1; i < argc; ++i )
 {
   nums=argv[i];
 // long a;
 // ::sscanf(argv[i], "%lx", &a); // read hex string and form long value
 // sum += a; // same as 'sum = sum + a'
 }
 int len = strlen(nums);

if(len<=2){
   unsigned long cur; 
   ::sscanf(nums, "%lx", &cur);
   if(cur<=128){
       std::cout<<cur;
   }
 }

  if(len=4){
   unsigned long cur;
   ::sscanf(nums, "%lx", &cur);
   char tr []= "0x";
   //std:: cout << cur<<"\n";
   unsigned long cur1 = nums & 0xff;
   unsigned long cur2 = cur >> 8;
   if(cur1 >128){
       //std :: cout <<cur1<<"\n";
       std::cout<<0;
   }
   else{
       unsigned long result = (cur2 - 128)*128 + cur1;
           std ::cout << result;
     }
   }


    system("pause");
   return 0;
}
4

1 回答 1

0

输入总是4个字符长吗?如果是这样的话 ...

#include <stdio.h>

int main(int argc, char *argv[]) {
    char num [] = "8751";
    int hi, lo;
    sscanf(num, "%2x%2x", &hi, &lo);
    printf("%s -> %d, %d\n", num, hi, lo);
}

打印8751 -> 135, 81。如果num被改变,你得到81ab -> 129, 171or a1b7 -> 161, 183

于 2012-10-06T04:52:50.293 回答