7-5 字节解析(parse_byte) PTA C++入门题答案

7-5 字节解析(parse_byte)

分数 10

全屏浏览题目

切换布局

作者 王政单位 山东大学

The size of the byte has historically been hardware-dependent and no definitive standards existed that mandated the size.

字节有几位都没个标准,古代程序员过的什么日子啊?还好现在字节统一成8位了。

鉴于我对C++已有相当牢固的基础,可以探索底层开发了,先做个解析十六进制字节数据的功能吧。

输入规格

  • 每项待读入的字节数据由两个非空白字符构成。

  • 如是正常的十六进制字节数据,高位在前、低位在后

  • 不区分大小写。

  • 各项之间由数量不定的空白符隔开。直接用cin读入即可,无需特殊处理。

输出规格

  • 每行输出一项:先输出读入的字符,间隔冒号和空格,再按十进制输出字节的数值。

样例输入

 0A    a3
Ff +z

样例输出

0A: 10
a3: 163
Ff: 255
+z: invalid

样例解释

  • 0A: 0 * 16 + 10 * 1 = 10

  • a3: 10 * 16 + 3 * 1 = 163

  • Ff: 15 * 16 + 15 * 1 = 255

  • +z含无效字符。

提示:后续题目用到类似功能,设计时请考虑重用性。

代码框架

#include<iostream>usingnamespacestd;
unsignedcharparse_byte(unsignedchar hi, unsignedchar lo){
return0; // TODO}
intmain(){
for(char hi, lo; cin >> hi >> lo;){
cout << hi << lo << ": ";
if(is_hex(hi) && is_hex(lo)){ // 重用cout << (int)parse_byte(hi, lo) << endl;
    }else{
cout << "invalid" << endl;
    }
  }
}

代码长度限制16 KB

时间限制200 ms

内存限制1 MB

答案

#include <iostream>
using namespace std;

int too(char v);
unsigned char parse_byte(unsigned char hi, unsigned char lo) 
{
    return too(hi) * 16 + too(lo);
}
int too(char c) 
{
    if (c >= 'a' && c <= 'f')return c - 'a' + 10;
    if (c >= 'A' && c <= 'F')return c - 'A' + 10;
    if (c >= '0' && c <= '9')return c - '0';
}
bool is_hex(char d) 
{
    if (d >= '0' && d <= '9' || d >= 'A' && d <= 'F' || d >= 'a' && d <= 'f')return true;
    return false;
}

int main() 
{
    for (char hi, lo; cin >> hi >> lo;) 
    {
        cout << hi << lo << ": ";
        if (is_hex(hi) && is_hex(lo)) { // 重用
            cout << (int)parse_byte(hi, lo) << endl;
        }
        else 
        {
            cout << "invalid" << endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lifesize/article/details/128945158