C语言 - Unicode编码与字符串互转

概述

        最近项目上需要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、总结

        希望能帮助到需要的攻城狮。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ch_champion

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值