C++ 从字符串转换为无符号长字符串并返回
如何将字符串转换为无符号长字符,以便无符号长字符将字符串中的字符表示为8位数字 提前谢谢 编辑:我要做的是将一个4个字符的字符串转换为ASCII码格式的相同4个字符的长字符串。假设“str”是字符串(std::string),而“res”是要写入的无符号长字符串。 像这样:C++ 从字符串转换为无符号长字符串并返回,c++,C++,如何将字符串转换为无符号长字符,以便无符号长字符将字符串中的字符表示为8位数字 提前谢谢 编辑:我要做的是将一个4个字符的字符串转换为ASCII码格式的相同4个字符的长字符串。假设“str”是字符串(std::string),而“res”是要写入的无符号长字符串。 像这样: for (std::string::iterator i = str.begin(); i != str.end(); ++i) { res <<= 8; res += *i; } for(st
for (std::string::iterator i = str.begin(); i != str.end(); ++i) {
res <<= 8;
res += *i;
}
for(std::string::iterator i=str.begin();i!=str.end();++i){
res基本上是相同的解决方案,对整数类型大小的假设较少,并检查可以通过这种方式转换的最大字符串大小:
#include <string>
#include <algorithm>
#include <iostream>
#include <climits>
int main()
{
const size_t MAX = sizeof(unsigned long);
std::string s("abcd");
unsigned long res = 0;
for (size_t i=0; i < std::min(MAX, s.size()); ++i)
{
res <<= CHAR_BIT;
res += (unsigned char) s[i];
}
std::cout << std::hex << res;
}
转换为无符号字符
适用于字符串包含高ASCII的情况,即大于127的值,在这种情况下字符
将为负数。请尝试字符串“\226\226\226\226”
,您将得到不正确的结果)
编辑:顺便说一句,在你的主题中,你说的是“and back”,所以这里是反向转换:
#include <limits>
std::string tostr(unsigned long x)
{
// this will mask out the lower "byte" of the number
const unsigned long mask = std::numeric_limits<unsigned char>::max();
if (x == 0)
return std::string("0");
std::string res;
for (; x > 0; x >>= CHAR_BIT) {
res += (char) (x & mask);
}
// we extracted the bytes from right to left, so need to reverse the result
std::reverse(res.begin(), res.end());
return res;
}
#包括
std::string tostr(无符号长x)
{
//这将掩盖数字中较低的“字节”
常量无符号长掩码=std::numeric_limits::max();
如果(x==0)
返回标准::字符串(“0”);
std::string res;
对于(;x>0;x>>=字符位){
res+=(字符)(x和掩码);
}
//我们从右向左提取字节,因此需要反转结果
std::reverse(res.begin(),res.end());
返回res;
}
字符是8位数字(通常)。你能重新表述你想要的吗?你已经问过这个问题了(基本上)。[编辑:我想我把DUP倒过来了;哦,好吧]可能是@balki的重复。你如何将res分配给它自己?还有,最后一行没有添加*I(即我们正在处理的字节)到res,而我们只想使res的前8位等于*i?谢谢你的回答。在显示它之前,你将res转换为十六进制格式。res最初是什么格式?你能解释一下“std::numeric_limits::max()”吗?大概是“11110000000000”,由“res+=(char)(x&mask)”所暗示?@Jona:res
是二进制的(与任何整数一样)。cout@Jona:这意味着“无符号字符所能容纳的最大值”,这是一种说0xFF
:)的奇特方式。我们需要屏蔽x的低位字节。请参阅
#include <limits>
std::string tostr(unsigned long x)
{
// this will mask out the lower "byte" of the number
const unsigned long mask = std::numeric_limits<unsigned char>::max();
if (x == 0)
return std::string("0");
std::string res;
for (; x > 0; x >>= CHAR_BIT) {
res += (char) (x & mask);
}
// we extracted the bytes from right to left, so need to reverse the result
std::reverse(res.begin(), res.end());
return res;
}