概述
最近项目上需要unicode编码与字符串互转,在此做个笔录。
1、编码环境为 visual studio 21,code如下:
#include <stdlib.h>
#include <stdio.h>
#include <string.h> 
#include <wchar.h>
#include <locale.h>
#include <math.h>
 
static void hex_data_to_log_data(unsigned char* src, int len, char* dst)
{
	int i = 0;
	int index = 0;
	char buff[1024] = { 0 };
	for (i = 0; i < len; i++) {
		index += sprintf(buff + index, "%02x", src[i]);
		if (i != len - 1)
			index += sprintf(buff + index, " ");
	}
	if (strlen(buff) > 0)
		strcpy(dst, buff);
}
 
static void print_hex_data(uint8_t* modbus_cmd, int len, const char* title)
{
	char log_modbus_data[1024] = {0};
	int size = len;
	int offset = 0;
	int print_len = 0;
	int count = 0;
	int max_len = 60;
 
	if (size <= max_len) {
		hex_data_to_log_data(modbus_cmd, size, log_modbus_data);
		if (strlen(log_modbus_data) > 0)
			printf("%s:%s", title, log_modbus_data);
	}
	else {
		while (size > 0) {
			count++;
			if (size > max_len)
				print_len = max_len;
			else
				print_len = size;
 
			hex_data_to_log_data(modbus_cmd + offset, print_len, log_modbus_data);
			if (strlen(log_modbus_data) > 0)
				printf("%s-%d:%s", title, count, log_modbus_data);
			offset += print_len;
			size -= print_len;
		}
	}
}
 
int asc_to_unicode(char* src, uint8_t* dst)
{
	wchar_t wStr[256] = {0};
	int index = 0;
	int i = 0;
 
	setlocale(LC_ALL, "");
	mbstowcs(wStr, src, 256);
	for (i = 0; i < wcslen(wStr); i++) {
		memcpy(dst + index, &wStr[i], 2);
		index += 2;
	}
	print_hex_data(dst, index, "asc_to_unicode");
 
	return index;
}
 
int unicode_to_asc(uint8_t* src, int src_len, char* dst)
{
	wchar_t wStr[256] = {0};
	uint16_t tmp_short;
	int index_cnt = 0;
	int j = 0;
 
	for (j = 0; j < src_len; j += 2) {
		memcpy(&tmp_short, src + j, 2);
		wStr[index_cnt++] = tmp_short;
	}
	wcstombs(dst, wStr, 256);
	printf("\nunicode_to_asc:%s\n", dst);
 
	return (int)strlen(dst);
}
 
int main(void)
{
	char asc[256] = {0};
	uint8_t hex[512] = {0};
	uint8_t str[] = "嘿嘿哈哈";
	asc_to_unicode((char*)str, hex);
	unicode_to_asc(hex, 12, asc);
	return(0);
} 
2、运行结果如下:

3、总结
希望能帮助到需要的攻城狮。



















