빅엔디엔과리틀엔디안 교환하는 함수구현에서 문의드립니다.
글쓴이: shean0 / 작성시간: 월, 2004/04/19 - 10:20오후
안녕하세요.. 제가 짠 소스인데요..
용도는 big-endian <=> little-endian으로 바꾸는것인데요.
이거 좀 더 효율적으로 할려구 하는데.. 제대로 되지가 않네요.
호출 int i=9;
change_big_little_buf(i,0,buf,sizeof(i)); 입력: i 또는 s
choic는 4또는 2
출력 : buf
void change_big_little_buf(int i,short int s,char *buf,int choice)
{
char tmp[4];
int ii; short int ss;
if( choice ==4)
{
#ifdef D_TEST0419
ii=ntohl(i); //ii=htonl(i)
memcpy(buf,&ii,4);
#else
memcpy(tmp,&i,4);
buf[3]=tmp[0];
buf[2]=tmp[1];
buf[1]=tmp[2];
buf[0]=tmp[3];
/* memcpy(&ii,buf,4);<==검증 */
#endif
}
else if(choice ==2)
{
memcpy(tmp,&s,2);
buf[1]=tmp[0];
buf[0]=tmp[1];
/* memcpy(&ss,buf,2); 검증 */
}
}Forums:


정말 많이 심심-_-해서 만들어 봤습니다. (C++ 코드입니다)효율적
정말 많이 심심-_-해서 만들어 봤습니다. (C++ 코드입니다)
효율적일지는 모르겠습니다만...
작성하고 나서 보니 암호같군요. -_-
#include <stdio.h> template< typename T > T conv( T & t ) { T n; char *cp = (char*) &n; char *tp = (char*) &t + sizeof(T); while( tp != (char*)&t ) { *cp++ = *--tp; } return n; } int main() { long long i64 = 0x1234567890ABCDEF; int i32 = 0x12345678; short i16 = 0x1234; printf( "0x%llX => 0x%llX\n", i64, conv( i64 ) ); printf( "0x%X => 0x%X\n", i32, conv( i32 ) ); printf( "0x%X => 0x%X\n", i32, conv( i32 ) ); printf( "0x%X => 0x%X\n", i16, conv( i16 ) ); }실행결과 :
그나저나 벌써 새벽 4시.. 왜이리 잠이 안오는 것인지 -_-
[code:1]#define Swap32IfLE(l)
제가 짠건 아니고..
[code:1]#include <stdio.h>unsi
#include <stdio.h> unsigned long conv( unsigned long x ) { unsigned long t = x; x = ( (x >> 8) | ( x & 0x000000ff ) << 24 ) & 0xff00ff00; t = ( (t << 8) | ( t & 0xff000000 ) >> 24 ) & 0x00ff00ff; return (x | t); } int main() { printf("SOURCE: %X\n", 0x12345678 ); printf("EXPECT: %X\n", 0x78563412 ); printf("CONVRT: %X\n", conv(0x12345678) ); return 0; }제 홈의 문제 중하나인데.. 공개!합니다..
---
http://coolengineer.com
[code:1] /* Big endian to little and
/* Big endian to little and back */ #define swaplong(a) \ ((((a)&0xff)<<24)+(((a>>8)&0xff)<<16)+(((a>>16)&0xff)<<8)+(((a>>24)&0xff))) #define swapshort(a) \ (((a)&0xff)<<8)+(((a>>8)&0xff)) #define my_htonl swaplong #define my_htons swapshort #define my_ntohl swaplong #define my_ntohs swapshort코드가 간결하긴 한데.. 쉬프트 연산이 많아서 그다지 효율적이진 않을거에요..^^
[quote]코드: [code:1]#define Swap32IfL
허... 옛날에 제가 짰던 코드하고 매크로 이름만 빼고 똑같이 생겼네요. 순간 깜짝 놀랐습니다.
댓글 달기