c++实现把一个short类型的值写入buffer中和从buffer中读出一个short类型值,buffer是char*类型请用二进制和文本实现
时间: 2023-12-14 16:39:05 浏览: 177
二进制方式:
将short类型的值写入buffer中:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char buffer[10];
short value = 12345;
memcpy(buffer, &value, sizeof(value));
// 输出buffer的内容
for (int i = 0; i < sizeof(value); i++) {
cout << (int)buffer[i] << " ";
}
cout << endl;
return 0;
}
```
从buffer中读取short类型的值:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char buffer[10] = {49, 57, 57, 57, 48, 0, 0, 0}; // short类型的值12345的二进制表示
short value;
memcpy(&value, buffer, sizeof(value));
cout << value << endl;
return 0;
}
```
文本方式:
将short类型的值写入buffer中:
```c++
#include <iostream>
#include <sstream>
using namespace std;
int main() {
char buffer[10];
short value = 12345;
stringstream ss;
ss << value;
string strValue = ss.str();
strcpy(buffer, strValue.c_str());
cout << buffer << endl;
return 0;
}
```
从buffer中读取short类型的值:
```c++
#include <iostream>
#include <sstream>
using namespace std;
int main() {
char buffer[10] = "12345";
short value;
stringstream ss;
ss << buffer;
ss >> value;
cout << value << endl;
return 0;
}
```
阅读全文