char和unsigned char在内存上都是占用一个字节,区别在于
(1)char取值范围:-128~+127,最高的bit是符号位
(2)unsigned char只能表示正数,不能表示负数,取值范围是0~255
(3)short取值范围:-32768~+32767
short占用两个字节,共16bit,能表示的数的个数是 2^16,总共65536个。 1)正负整数各有一半的数量,负整数的取值范围是-32768 ~ -1,共32768个; 2)0 算一个; 3)正整数取值范围是 1 ~ 32767 共32767个; 4)一共就有32768+1+32767=65536个数。 |
#include
#include
typedef unsigned char uint8_t;
int main(void)
{
int i, j;
uint8_t a[10]={1,1,1,1,1,1,1,1,1,1};
uint8_t c[10];
short b[5];
for(i=0, j=0; i<5; i++)
b[i]=(a[j+1]<<8|a[j]);
for(i=0; i<5; i++)
printf("%04x ", b[i]);
printf("\n");
for(i=0, j=0; i<5; i++) {
c[j]=b[i]&0xff; //low 8bit
c[j+1]=((b[i]>>8)&0xff); //high 8bit
j=j+2;
}
for(i=0; i<10; i++)
printf("%d ", c[i]);
printf("\n");
return 0;
}
打印:
0101 0101 0101 0101 0101 1 1 1 1 1 1 1 1 1 1 |
#include
#include
typedef unsigned char uint8_t;
int main(void)
{
int i, j;
unsigned char a[10]={1,2,3,4,5,6,7,8,9,0};
short *b=(short *)a;
uint8_t c[10];
for(i=0, j=0; i<5; i++) {
c[j]=b[i]&0xff;
c[j+1]=(b[i]>>8)&0xff;
j=j+2;
}
for(i=0; i<10; i++)
printf("%d ", c[i]);
printf("\n");
return 0;
}
输出:1 2 3 4 5 6 7 8 9 0
#include
#include
typedef unsigned char uint8_t;
int main(void)
{
int i, j;
uint8_t a[10]={1,2,3,4,5,6,7,8,9,0};
short *b=(short *)a;
short c[5];
uint8_t d[10];
#if 0
/*
//memcpy在内存上是按照1 byte的长度进行赋值(拷贝)
//所以这里拷贝5是错的, 拷贝不完全
//memcpy(c, b, 5);
*/
//memcpy(c, b, 10);
#else
for(i=0; i<5; i++)
c[i]=b[i];
#endif
for(i=0, j=0; i<5; i++) {
d[j]=c[i]&0xff;
d[j+1]=(c[i]>>8)&0xff;
j=j+2;
}
printf("\n");
for(i=0; i<10; i++)
printf("%d ", d[i]);
printf("\n");
return 0;
}
打印输出:1 2 3 4 5 6 7 8 9 0
#include
#include
typedef unsigned char uint8_t;
int main(void)
{
int i, j;
unsigned char a[10]={1,2,3,4,5,6,7,8,9,0};
short *b=(short *)a; //char to short
char *c=(char*)b; //short to char
for(i=0; i<10; i++)
printf("%d ", c[i]);
printf("\n");
return 0;
}
打印输出:1 2 3 4 5 6 7 8 9 0
这种方式简介明了,省空间,运行效率也高。
#include
#include
typedef unsigned char uint8_t;
int main(void)
{
int i, j;
unsigned char a[10]={1,2,3,4,5,6,7,8,9,0};
short *b=(short *)a; //char to short
short dat[5];
memcpy(dat, b, 10);
char *c=(char*)dat; //short to char
for(i=0; i<10; i++)
printf("%d ", c[i]);
printf("\n");
return 0;
}
打印输出:1 2 3 4 5 6 7 8 9 0
#include
#include
typedef unsigned char uint8_t;
int main(void)
{
int i, j;
unsigned char a[10]={1,1,1,1,1,1,1,1,1,1};
short *b=(short *)a; //char to short
short dat[5];
memcpy(dat, b, 10);
for(i=0; i<5; i++)
dat[i]=dat[i]+1;
char *c=(char*)dat; //short to char
for(i=0; i<10; i++)
printf("%d ", c[i]);
printf("\n");
return 0;
}
打印输出:2 1 2 1 2 1 2 1 2 1