从字符串转换为 uint8,反之亦然

Casting from string to uint8 and vice versa

本文关键字:反之亦然 uint8 字符串 转换      更新时间:2023-10-16

我正在为图像版本制作GUI,我需要显示和处理来自用户的RGB值。因此,我使用 uint8_t 来存储这些值和字符串流来从/到字符串获取/设置值。我的问题是uint8_t被视为字符,因此强制转换仅返回字符串的第一个字符。

例:假设我设置了输入字符串"123",我的返回值将是 49(ASCII 代码"1"(

由于我使用模板化函数进行强制转换,因此我希望对代码进行尽可能少的更改(当然(。这是我使用的转换函数:

template<typename T>
T Cast(const std::string &str) {
    std::stringstream stream;
    T value;
    stream << str;
    stream >> value;
    if (stream.fail()) {
        Log(LOG_LEVEL::LERROR, "XMLCast failed to cast ", str, " to ", typeid(value).name());
    }
    return value;
}

所以当我这样做时

uint8_t myInt = Cast<uint8_t>("123");

我得到 49 而不是 123,知道吗?

似乎演员

不是这里工作的正确工具。强制转换是将一个值重新解释为给定类型或将相似的类型相互转换(想想,双精度为 int,反之亦然或基类指针指向派生类指针(。字符串和整数类型以这种方式不密切相关。我认为您要做的是将字符串显式转换为整数,这表明std::stoi()是您想要的。

void Foo( const std::string& str ) 
{
    const auto i = std::stoi( str );
    std::cout << i << 'n';
    // ...
}
int main()
{
    Foo( "123" );
}

印刷品: 123 .在科利鲁上直播。

您需要

先将值读取为unsigned (short) int(如果您愿意,可以uint(16|32)_t(,然后可以将其截断为uint8_t。由于您的函数是模板化的,因此您只需为uint8_t提供专用化,以不同于其他类型的方式处理它:

template<>
uint8_t Cast<uint8_t>(const std::string &str) {
    std::istringstream stream(str);
    uint16_t value;
    if ((!(stream >> value)) || (value > 0x00FF)) {
        Log(LOG_LEVEL::LERROR, "XMLCast failed to cast ", str, " to ", typeid(uint8_t).name());
    }
    return static_cast<uint8_t>(value);
}