[求助] big endian 与 little endian之间的转换
ptr是指向需要转换对象的指针,size是该对象所占的byte数。
#include <stdio.h>
void *ConvertEndian(void *ptr, size_t size)
{
char *head = (char *)ptr;
char *tail = head + size -1;
char temp;
for(; tail > head; tail--, head++)
{
temp = *head;
*head = *tail;
*tail = temp;
}
}
char* strrev(char* s)
{
/* h指向s的头部 */
char* h = s;
char* t = s;
char ch;
/* t指向s的尾部 */
while(*t++){};
t--; /* 与t++抵消 */
t--; /* 回跳过结束符'\0' */
/* 当h和t未重合时,交换它们所指向的字符 */
while(h < t)
{
ch = *h;
*h++ = *t; /* h向尾部移动 */
*t-- = ch; /* t向头部移动 */
}
return(s);
}
void swap_byte_order(void *buf,int bytes) {
unsigned char t,*b=(unsigned char *)buf;
for (int i=0;i<bytes/2;i++) {
t=b[i];
b[i]=b[bytes-1-i];
b[bytes-1-i]=t;
}
}
short s;int k;long L;
swap_byte_order(&s,sizeof(s));
swap_byte_order(&k,sizeof(k));
swap_byte_order(&L,sizeof(L));
# include <stdio.h>
void ConvertEndian(void * ptr, size_t size)
{
char * head = (char *)ptr;
char * tail = head + size - 1;
char temp;
for( ; tail > head; tail--, head++)
{
temp = *head;
*head = *tail;
*tail = temp;
}
}
int main()
{
short a = 0x1234;
int b = 0x12345678;
ConvertEndian(&a, sizeof(a));
ConvertEndian(&b, sizeof(b));
printf("%hx\n", a);
printf("%x\n", b);
return 0;
}