gpt4 book ai didi

c++ - 将 char* 转换为 int

转载 作者:行者123 更新时间:2023-11-28 06:30:24 24 4
gpt4 key购买 nike

我目前正在尝试将整数转换为 char* 以便通过套接字发送它。在接收方法中,我逻辑上尝试再次将 char* 视为整数,但我似乎遗漏了一些东西,因为我无法正确处理。

#include <iostream>

using namespace std;

int main(int argc, char** argv) {

int num1 = 42; // Works
int num2 = 100; // Works
int num3 = 126; // Works
int num4 = 517; // Doesn't seem to work for int > 127

char p1[sizeof(int)];
*p1 = num1;
char p2[sizeof(int)];
*p2 = num2;
char p3[sizeof(int)];
*p3 = num3;
char p4[sizeof(int)];
*p4 = num4;

void* pA = p4;
void* pB = &num4;

int result1 = static_cast<int>(*p1);
int result2 = static_cast<int>(*p2);
int result3 = static_cast<int>(*p3);
int result4 = static_cast<int>(*p4);

int resultV1 = *static_cast<int*>(pA);
int resultV2 = *reinterpret_cast<int*>(p3);
unsigned int resultV3 = static_cast<int>(*p4);
int resultV4 = *static_cast<int*>(pB); // Works, but I need to convert a char* into an int, not a void* into an int

cout << "R1: " << result1 << endl;
cout << "Expected: " << num1 << endl << endl;
cout << "R2: " << result2 << endl;
cout << "Expected: " << num2 << endl << endl;
cout << "R3: " << result3 << endl;
cout << "Expected: " << num3 << endl << endl;
cout << "R4: " << result4 << endl;
cout << "Expected: " << num4 << endl << endl;
cout << "RV1: " << resultV1 << endl;
cout << "Expected: " << num4 << endl << endl;
cout << "RV2: " << resultV2 << endl;
cout << "Expected: " << num4 << endl << endl;
cout << "RV3: " << resultV3 << endl;
cout << "Expected: " << num4 << endl << endl;
cout << "RV4: " << resultV4 << endl;
cout << "Expected: " << num4 << endl << endl;

getchar();
return 0;
}

我现在完全不知道如何解决这个问题。我尝试了其他几种方法,但它们似乎都无法正常工作。必须首先将整数转换为 char*,因为 WinSock-API 中的 recv() 方法将其读取的字节存储在缓冲区字符数组中。

任何解释或解决方案?提前致谢。

最佳答案

如果你不想使用 C 风格的指针,也许你可以试试这个。

void int2CharArr(int num, char* p1){
p1[0] = num & 0xFF;
p1[1] = (num >> 8) & 0xFF;
p1[2] = (num >> 16) & 0xFF;
p1[3] = (num >> 24) & 0xFF;
}

int charArr2Int(char* p1){
return (p1[3] << 24) + (p1[2] << 16) + (p1[1] << 8) + p1[0];
}

void test(){
int a = 0x12345678;
char q[sizeof(int)];
int2CharArr(a, q);
int b = charArr2Int(q);
printf("%x , %x , %x , %x\n", *q, *(q+1), *(q+2), *(q+3));
printf("%x\n", b);
}

关于c++ - 将 char* 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27700344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com