单个unicode字符转utf-8

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void UnicodeodeToUtf8(const char *unicode, unsigned char *utf8,
		int unicode_size)
{
	int temp = 0;
	memcpy(&temp, unicode, unicode_size);
	if (temp <= 0x0000007F)
	{
		*utf8 = (temp & 0x7F);
	}
	else if (temp >= 0x00000080 && temp <= 0x000007FF)
	{
		*utf8 = ((temp >> 6) & 0x1F) | 0xC0;
		*(utf8 + 1) = (temp & 0x3F) | 0x80;
	}
	else if (temp >= 0x00000800 && temp <= 0x0000FFFF)
	{
		*utf8 = ((temp >> 12) & 0x0F) | 0xE0;
		*(utf8 + 1) = ((temp >> 6) & 0x3F) | 0x80;
		*(utf8 + 2) = (temp & 0x3F) | 0x80;
	}
	else if (temp >= 0x00010000 && temp <= 0x001FFFFF)
	{
		*utf8 = ((temp >> 18) & 0x07) | 0xF0;
		*(utf8 + 1) = ((temp >> 12) & 0x3F) | 0x80;
		*(utf8 + 2) = ((temp >> 6) & 0x3F) | 0x80;
		*(utf8 + 3) = (temp & 0x3F) | 0x80;
	}
	else if (temp >= 0x00200000 && temp <= 0x03FFFFFF)
	{
		*utf8 = ((temp >> 24) & 0x03) | 0xF8;
		*(utf8 + 1) = ((temp >> 18) & 0x3F) | 0x80;
		*(utf8 + 2) = ((temp >> 12) & 0x3F) | 0x80;
		*(utf8 + 3) = ((temp >> 6) & 0x3F) | 0x80;
		*(utf8 + 4) = (temp & 0x3F) | 0x80;
	}
	else if (temp >= 0x04000000 && temp <= 0x7FFFFFFF)
	{
		*utf8 = ((temp >> 30) & 0x01) | 0xFC;
		*(utf8 + 1) = ((temp >> 24) & 0x3F) | 0x80;
		*(utf8 + 2) = ((temp >> 18) & 0x3F) | 0x80;
		*(utf8 + 3) = ((temp >> 12) & 0x3F) | 0x80;
		*(utf8 + 4) = ((temp >> 6) & 0x3F) | 0x80;
		*(utf8 + 5) = (temp & 0x3F) | 0x80;
	}
}

你可能感兴趣的:(unicode,unicode,unicode,utf-8,utf-8)