C++下字符串与无符号数之间的转换

    /**
     * @brief GetString0x16 byte数组转string(16进制格式)
     * @param bArray 数组
     * @param bArray_len 数组长度
     * @param offset 偏移量
     * @param size 待处理字节数
     * @return 16进制形式字符串
     */
    string  GetString0x16(unsigned char *bArray, int bArray_len, int offset, int size)
	{
		if (bArray == NULL) {
			return string();
		}
		if (bArray_len < offset + size) {
			return string();
		}
		string strHex;
		strHex.resize(2 * bArray_len);
		int nIndex = 0;
		for (int i = offset; i < offset+size; i++)
		{
			int high = bArray[i] / 16, low = bArray[i] % 16;
			strHex[nIndex] = (high < 10) ? ('0' + high) : ('A' + high - 10);
			strHex[nIndex + 1] = (low < 10) ? ('0' + low) : ('A' + low - 10);
			nIndex += 2;
		}
		return strHex;
	}
    
    /**
     * @brief GetBytes0X16 string转byte数组(16进制格式)
     * @param data_text string数据
     * @param data byte数据
     */
	void  GetBytes0x16(string str, unsigned char* data)
	{
		int hexdata, lowhexdata;
		int hexdatalen = 0;
		int len = str.length();
		char lstr, hstr;
		for (int i = 0; i < len; )
		{
			hstr = str[i];
			if (hstr == ' ')
			{
				i++;
				continue;
			}
			i++;
			if (i >= len)
				break;
			lstr = str[i];
			hexdata = ConvertHexChar(hstr);
			lowhexdata = ConvertHexChar(lstr);
			if ((hexdata == 16) || (lowhexdata == 16))
				break;
			else
				hexdata = hexdata * 16 + lowhexdata; i++;
			data[hexdatalen] = (char)hexdata;
			hexdatalen++;
		}
	}
    /**
     * @brief ReadUint16 从字符数组中读取无符号16位整数
     * @param data 字节数组
     * @param start 开始读取位置
     * @return 字符数组中的Uint16整数
     */
	uint16_t ReadUint16(unsigned char* data, int start) {
		unsigned char data1 = data[start];
		unsigned char data2 = data[start + 1];
		return (uint16_t)(data1 << 8) | data2;
	}
    /**
     * @brief WriteUint16 将无符号16位整数写入字符数组中
     * @param data 被写入字节数组
     * @param start 开始写入位置
     * @param value   无符号16位整数
     */
	void WriteUint16(unsigned char* data, int start, uint16_t value) {
		data[start] = (unsigned char)((value >> 8) & 0xFF);
		data[start + 1] = (unsigned char)((value) & 0xFF);
	}
    /**
     * @brief ReadUint32 从字符数组中读取无符号32位整数
     * @param data 字节数组
     * @param start 开始读取位置
     * @return 字符数组中的Uint32整数
     */
	uint32_t ReadUint32(unsigned char* data, int start) {
		unsigned char data1 = data[start];
		unsigned char data2 = data[start + 1];
		unsigned char data3 = data[start + 2];
		unsigned char data4 = data[start + 3];
		return (uint32_t)((data1 << 24) | (data2 << 16) | (data3 << 8) | data4);
	}
    /**
     * @brief WriteUint32 将无符号32位整数写入字符数组中
     * @param data 字节数组
     * @param start 开始输入位置
     * @param value 无符号32位整数
     */
	void WriteUint32(unsigned char*data, int start, uint32_t value) {
		data[start] = (unsigned char)((value >> 24) & 0xFF);
		data[start + 1] = (unsigned char)((value >> 16) & 0xFF);
		data[start + 2] = (unsigned char)((value >> 8) & 0xFF);
		data[start + 3] = (unsigned char)((value) & 0xFF);
	}

 

你可能感兴趣的:(C++下字符串与无符号数之间的转换)