uint8_t和char的相互转换

        uint8_t *和char*的相互转换以及uint8_t *和int16_t*的相互转换

        实际应用需要,实现uint8、int16_t、int32_t的按字节传输,实现发送和接收功能。如int16_t,需要将int16_t转为2字节发送,再接收两个字节解码转回为Int16_t。

intx与char *的转换:

#include 
using namespace std;

int main()
{
	unsigned char buff[7] = {0x00};

	unsigned char a = 12;
	int16_t b = 13;
	int32_t c = 14;

	buff[0] = a;

	char temp1[2] = "\0";
	*(int16_t *)temp1 = (int16_t)b;
	buff[1] = temp1[0];
	buff[2] = temp1[1];

	char temp2[4] = "\0";
	*(int32_t *)temp2 = (int32_t)c;
	buff[3] = temp2[0];
	buff[4] = temp2[1];
	buff[5] = temp2[2];
	buff[6] = temp2[3];

	std::cout << hex << int(a) << " -> " << int(buff[0]) << endl;
	std::cout << hex << int(b) << " -> " << int(buff[2]) << int(buff[1]) << endl;
	std::cout << hex << int(c) << " -> " << int(buff[6]) << int(buff[5]) << int(buff[4]) << int(buff[3]) << endl;

	std::cout << "解析:" << endl;
	unsigned char a1 = buff[0];
	char t1[2] = {buff[1], buff[2]};
	int16_t b1 = *((int16_t *)t1);
	char t2[4] = {buff[3], buff[4], buff[5], buff[6]};
	int32_t c1 = *((int32_t *)t2);
	std::cout << hex << "a1 = " << int(a1) << ", " << dec << int(a1) << endl;
	std::cout << hex << "b1 = " << int(b1) << ", " << dec << int(b1) << endl;
	std::cout << hex << "c1 = " << int(c1) << ", " << dec << int(c1) << endl;
}

结果:

 std::hex 以十六进制显示;

std::dec 以十进制形式显示;

std::oct 以八进制形式显示。

你可能感兴趣的:(c++,c++,windows,ajax)