嘿伙计们,我的任务基本上是从char获取小数。例如,输入参数是8751.我怎样才能得到51(仅)转换为十进制?我知道如何得到87,我也知道如果它是十六进制的如何得到51(0x8751& 0xff)。
所以我的程序的输出将是:
(0x87 & 0x7f)*128 + (0x51)
OR
(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;
}
答案 0 :(得分: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, 171
或a1b7 -> 161, 183
。