从字符串转换为 uint8,反之亦然
Casting from string to uint8 and vice versa
我正在为图像版本制作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);
}
相关文章:
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 从值小于256的uint16到uint8的Endian安全转换
- 在C++中,将int值赋给enum,反之亦然
- 如何在 c++ 中将所有大写字母转换为字符串中的小写字母,反之亦然?
- 将通用引用强制转换为可调用的 void 指针,反之亦然
- 用非原子更新原子变量,反之亦然
- 从向量到空指针的 memcpy(反之亦然)不起作用
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 你能把一个向量<int64>投射到一个向量<uint8>吗
- 如何在 OpenCL 中将小写转换为大写,反之亦然
- SSCANF 进入 uint8 阵列失败
- 如何将CNG密钥转换为OpenSSL EVP_PKEY(反之亦然)?
- C++ - 使用结构数据类型将单词中的单个小写字符更改为大写,反之亦然
- 着色器将uint8投射到float,并将其重新解释回uint
- 快速将无符号字符的向量强制转换为POD结构的向量,反之亦然
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 将指针uint8覆盖到指针uint16
- 创建一个包含30亿个uint8元素的向量
- 使用C++将越南语字符从ISO88591、UTF8、UTF16BE、UTF16LE和UTF16编码为十六进制,反之亦然
- 从字符串转换为 uint8,反之亦然