C++中string转bytearray
时间: 2023-11-20 22:07:29 浏览: 169
在 C 语言中,可以使用指针和字符数组来实现字符串转字节数组的功能。以下是一个示例代码,将字符串转换为字节数组:
```
#include<stdio.h>
#include<string.h>
int main() {
char str[] = "Hello, world!"; // 声明一个字符串
int len = strlen(str); // 获取字符串的长度
char byteArr[len]; // 声明一个字节数组,长度为字符串的长度
for (int i = 0; i < len; i++) {
byteArr[i] = str[i]; // 将字符串中的每个字符赋值给字节数组
}
printf("String: %s\n", str);
printf("Byte Array: ");
for (int i = 0; i < len; i++) {
printf("%d ", byteArr[i]); // 输出每个字节的整数值
}
printf("\n");
return 0;
}
```
在上述代码中,使用了 `strlen` 函数获取字符串的长度,然后声明了一个同样长度的字节数组。接着,使用循环将字符串中的每个字符赋值给字节数组。最后,使用循环输出字节数组中每个字节的整数值。
相关问题
C++中string转byte数组
可以使用string的c_str()函数获得一个指向字符数组的指针,然后使用memcpy函数将字符数组复制到byte数组中。具体实现如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string str = "hello world";
const char* charArray = str.c_str();
int length = str.length();
unsigned char byteArray[length];
memcpy(byteArray, charArray, length);
for(int i = 0; i < length; i++) {
printf("%02x", byteArray[i]);
}
cout << endl;
return 0;
}
```
输出结果为:
```
68656c6c6f20776f726c64
```
其中,68656c6c6f20776f726c64 是 "hello world" 的十六进制表示。
string 转BYTE c++
在C++中,将字符串转换为字节数组(byte array)可以通过以下方式实现:
1. 使用std::string的c_str()函数获取字符串的C风格字符数组。
2. 使用std::vector<char>来存储字节数组。
3. 使用std::copy()函数将C风格字符数组复制到std::vector<char>中。
下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
std::string str = "Hello, World!";
// 获取C风格字符数组
const char* cstr = str.c_str();
// 将C风格字符数组复制到字节数组
std::vector<char> byteArray(cstr, cstr + str.size());
// 输出字节数组
for (char byte : byteArray) {
std::cout << static_cast<int>(byte) << " ";
}
return 0;
}
```
运行以上代码,将输出字符串 "Hello, World!" 的字节数组表示形式。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)