Skip to content

Instantly share code, notes, and snippets.

@pallove
Created August 26, 2014 03:15
Show Gist options
  • Save pallove/d0bf17ff1ea179c77300 to your computer and use it in GitHub Desktop.
Save pallove/d0bf17ff1ea179c77300 to your computer and use it in GitHub Desktop.
打印一段utf-8字符
#include <stdio.h>
#include <string.h>
void write_value(char *c, int value, int head, int tail, int len)
{
int high = value >> 8;
int low = (1 << 8) - 1 & value;
if (len == 1) {
c[0] = low | head;
}
else if(len == 2) {
c[0] = head | ((high & 7) << 2) | (low >> 6);
c[1] = tail | ((1 << 6) - 1 & low);
}
else if(len == 3) {
c[0] = head | (high >> 4);
c[1] = tail | ((high & 15) << 2) | (low >> 6);
c[2] = tail | ((1 << 6) - 1 & low);
}
printf("unicode=%#x, char:%.*s\n", value, len, c);
}
void print_char(char *c, int start, int end)
{
if (start > end) {
int tmp = start;
start = end;
end = tmp;
}
int head, tail, len;
int value = 0;
int i = 0;
for(; i < end - start; i++) {
value = start + i;
if (value > 0 && value <= 0x7f) {
head = tail = 0;
len = 1;
}
else if (value >= 0x80 && value <= 0x7ff) {
head = 0xc0;
tail = 0x80;
len = 2;
}
else if (value >= 0x800 && value <= 0xffff) {
head = 0xe0;
tail = 0x80;
len = 3;
}
write_value(c + i * len, value, head, tail, len);
}
}
int main(void)
{
char c[10000];
print_char(c, 15000, 15200);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment