본문 바로가기
  • fishing...
  • eating...
MISCELLANEOUSNESS

실수 데이터 타입 직렬화

by 회색뿔 2013. 5. 13.



bit연산으로 하게 되면 신경써야 할게 많다. 논리적 오류와 floating 연산에 의한 오차도 상당함을 알 수 있다.


union을 활용한 데이터 직렬화 방법을 찾았다. (union에 대한 자세한 설명)

floating number를 직렬화 하는 방법을 찾던 중 아래와 같은 방법을 찾았다. 활용도가 매우 높으리라 생각된다. 


    
typedef union SERIALIZE_DOUBLE{
        double         d;
        unsigned char  bytes[sizeof(double)];
}SDOUBLE;

typedef union SERIALIZE_FLOAT{
        float         f;
        unsigned char  bytes[sizeof(float)];
}SFLOAT;

unsigned char* serialize_double(unsigned char* buffer, double x) {
    int i;
	SDOUBLE u;

    u.d = x;
    for (i=0; i < sizeof(double); ++i)
    {
		buffer[i] = u.bytes[i];
	}

	return u.bytes;
}

double deserialize_double(unsigned char* buffer) {
    int i;
    SDOUBLE u;

	for( i=0; i < sizeof(double); ++i )
	{
		u.bytes[i] = buffer[i];
	}

	return u.d;
}

unsigned char* serialize_float(unsigned char* buffer, float x) {
    int i;
	SFLOAT u;

    u.f = x;
    for (i=0; i < sizeof(double); ++i)
    {
		buffer[i] = u.bytes[i];
	}

	return u.bytes;
}

float deserialize_float(unsigned char* buffer) {
    int i;
    SFLOAT u;

	for( i=0; i < sizeof(double); ++i )
	{
		u.bytes[i] = buffer[i];
	}

	return u.f;
}

http://stackoverflow.com/questions/3418319/serialize-double-and-float-with-c


'MISCELLANEOUSNESS' 카테고리의 다른 글

초대장 배포  (75) 2013.06.18
바탕화면  (0) 2013.02.06
Multi Reader 장착  (0) 2013.01.23