c++98,将int a = 1,转为八位的string b = "00000001",同理int d = 324,转为八位的string b = "00000324",,再将b转为vector<uint8_t> c
时间: 2024-03-16 20:46:39 浏览: 74
可以使用以下代码将 int 转为八位的 string:
```cpp
#include <iostream>
#include <string>
#include <vector>
std::string intToEightBitString(int num)
{
std::string res = "";
for (int i = 0; i < 8; i++)
{
res = (char)((num & 1) + '0') + res;
num >>= 1;
}
return res;
}
```
然后可以使用以下代码将 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>
std::string intToEightBitString(int num)
{
std::string res = "";
for (int i = 0; i < 8; i++)
{
res = (char)((num & 1) + '0') + res;
num >>= 1;
}
return res;
}
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 a = 1;
std::string b = intToEightBitString(a);
std::cout << "a: " << a << ", b: " << b << std::endl;
int d = 324;
std::string e = intToEightBitString(d);
std::cout << "d: " << d << ", e: " << e << 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;
std::vector<uint8_t> f = stringToVector(e);
std::cout << "f: ";
for (int i = 0; i < f.size(); i++)
{
std::cout << (int)f[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
阅读全文