리틀 엔디안을 빅 엔디안으로,
빅 엔디안을 리틀 엔디안으로 변환하는 함수에 대해 알아보자.
배고파서 밥 묵러 가야지.
잘 안대 윈도우즈에서는..
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdint.h>
/*
#include <endian.h>
void print_endian() {
if (__BYTE_ORDER == __LITTLE_ENDIAN) {
printf("Little-endian\\r\\n");
}
else if (__BYTE_ORDER == __BIG_ENDIAN) {
printf("Big-endian\\n\\r\\n");
}
else {
printf("Unknown endian\\r\\n");
}
}
*/
void print_endian() {
uint32_t dummy_val = 1;
uint32_t* addr_of_dummy_val = (uint32_t*) &dummy_val;
if (*addr_of_dummy_val == 1) {
printf("Little-endian\\r\\n");
}
else {
printf("Big-endian\\r\\n");
}
}
void conv_big2little_endian(uint32_t val) {
}
void conv_little2big_endian(uint32_t val) {
// 0xDDCCBBAA > 0xAABBCCDD
uint32_t resul = 0;
result |= (val >> 24) & 0xFF;
}
//#include <arpa/inet.h> // 윈도우에서는 이거 안먹음
#include <WinSock2.h>
int main(void) {
print_endian();
uint32_t foo = 0xDDCCBBAA;
printf("foo = 0x%02X\\r\\n", foo);;
uint32_t conv_val = ntohl((unsigned long)foo);
printf("converted value = %02X", conv_val);
//conv_big2little_endian(foo);
return 0;
}
/*
#include <stdio.h>
//#include <arpa/inet.h>
//#include <WinSock2.h>
#include <winsock.h>
int main(void)
{
long host_byte = 0x12345678;
printf("%x to %x\\n", host_byte, htonl(host_byte));
return 0;
}
*/
//#pargma comment(lib, "ws2_32")
#include <winsock2.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
return 1;
u_short x1 = 0x1234;
u_long y1 = 0x12345678;
u_short x2;
u_long y2;
// 호스트 바이트 → 네트워크 바이트
printf("[호스트 바이트 -> 네트워크 바이트]\\n");
printf("0x%x -> 0x%x\\n", x1, x2 = htons(x1));
printf("0x%x -> 0x%x\\n", y1, y2 = htonl(y1));
// 네트워크 바이트 → 호스트 바이트
printf("[네트워크 바이트 -> 호스트 바이트]\\n");
printf("0x%x -> 0x%x\\n", x2, ntohs(x2));
printf("0x%x -> 0x%x\\n", y2, ntohl(y2));
// 잘못된 사용 예
printf("[잘못된 사용 예]\\n");
printf("0x%x -> 0x%x\\n", x1, htonl(x1));
//WSACleanup()
return 0;
}
▼ 엔디안 방식에 구애 받지 않는 C 코드 작성하기
https://dataonair.or.kr/db-tech-reference/d-lounge/technical-data/?mod=document&uid=237549