c++98,将int d = 324,转为八位的string b = "00000324",,再将b转为vector<uint8_t> c
时间: 2024-03-16 18:46:44 浏览: 107
如何将int 转为string(c/c++)
可以使用以下代码将 int 转为八位的 string:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
std::string intToEightBitString(int num)
{
std::stringstream ss;
ss << std::setw(8) << std::setfill('0') << num;
return ss.str();
}
```
然后可以使用以下代码将 string 转为 vector<uint8_t>:
```cpp
std::vector<uint8_t> stringToVector(const std::string& str)
{
std::vector<uint8_t> res;
for (int i = 0; i < str.size(); i += 8)
{
uint8_t byte = 0;
for (int j = 0; j < 8; j++)
{
byte = (byte << 1) + (str[i + j] - '0');
}
res.push_back(byte);
}
return res;
}
```
完整代码如下:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
std::string intToEightBitString(int num)
{
std::stringstream ss;
ss << std::setw(8) << std::setfill('0') << num;
return ss.str();
}
std::vector<uint8_t> stringToVector(const std::string& str)
{
std::vector<uint8_t> res;
for (int i = 0; i < str.size(); i += 8)
{
uint8_t byte = 0;
for (int j = 0; j < 8; j++)
{
byte = (byte << 1) + (str[i + j] - '0');
}
res.push_back(byte);
}
return res;
}
int main()
{
int d = 324;
std::string b = intToEightBitString(d);
std::cout << "d: " << d << ", b: " << b << std::endl;
std::vector<uint8_t> c = stringToVector(b);
std::cout << "c: ";
for (int i = 0; i < c.size(); i++)
{
std::cout << (int)c[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
阅读全文