Front-end_dev

엔디언 변환 본문

C

엔디언 변환

Eat2go 2018. 4. 27. 19:18


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const uint8_t val8 = 101
const uint16_t val16 = 10001
const uint32_t val32 = 100000001
const uint64_t val64 = 1000000000001L; 
const int MESSAGELENGTH = sizeof(uint8_t) + sizeof(uint16_t) + sizeof(uint32_t)
    + sizeof(uint64_t);
 
static char stringBuf[BUFSIZE];
char *BytesToDecString(uint8_t *byteArray, int arrayLength) {
  char *cp = stringBuf;
  size_t bufSpaceLeft = BUFSIZE;
  for (int i = 0; i < arrayLength && bufSpaceLeft > 0; i++) {
    int strl = snprintf(cp, bufSpaceLeft, "%u ", byteArray[i]);
    bufSpaceLeft -= strl;
    cp += strl;
  }
  return stringBuf;
}

int EncodeIntBigEndian(uint8_t dst[], uint64_t val, int offset, int size) {
  for (int i = 0; i < size; i++) {
    dst[offset++= (uint8_t) (val >> ((size - 1- i) * CHAR_BIT);
  }
  return offset;
}
 
uint64_t DecodeIntBigEndian(uint8_t val[], int offset, int size) {
  uint64_t rtn = 0;
  for (int i = 0; i < size; i++) {
    rtn = (rtn << CHAR_BIT) | val[offset + i];
  }
  return rtn;
}
 
int main(int argc, char *argv[]) {
  uint8_t message[MESSAGELENGTH]; 
 
  int offset = 0;
  offset = EncodeIntBigEndian(message, val8, offset, sizeof(uint8_t));
  offset = EncodeIntBigEndian(message, val16, offset, sizeof(uint16_t));
  offset = EncodeIntBigEndian(message, val32, offset, sizeof(uint32_t));
  offset = EncodeIntBigEndian(message, val64, offset, sizeof(uint64_t));
  printf("Encoded message:\n%s\n", BytesToDecString(message, MESSAGELENGTH));
 
  uint64_t value =
      DecodeIntBigEndian(message, sizeof(uint8_t), sizeof(uint16_t));
  printf("Decoded 2-byte integer = %u\n", (unsigned int) value);
  value = DecodeIntBigEndian(message, sizeof(uint8_t) + sizeof(uint16_t), sizeof(uint32_t));
  printf("Decoded 4-byte integer = %llu\n", value);
  value = DecodeIntBigEndian(message, sizeof(uint8_t) + sizeof(uint16_t)
      + sizeof(uint32_t), sizeof(uint64_t));
  printf("Decoded 8-byte integer = %llu\n", value);
}
cs

10101001 11100011 11001100 10011001를 예로들어서 설명할경우,

EncodeIntBigEndian 함수에서의 내부로직 (dst[offset++= (uint8_t) (val >> ((size - 1- i) * CHAR_BIT);)
(코드에서 1바이트로 캐스팅 하는거 무시한다고 가정)
[0] 00000000 00000000 00000000 10101001 >> 24
[1] 00000000 00000000 10101001 11100011 >> 16
[2] 00000000 10101001 11100011 11001100 >> 8
[3] 10101001 11100011 11001100 10011001 >> 0

DecodeIntBigEndian 함수내에서의 로직 (rtn = (rtn << CHAR_BIT) | val[offset + i];)
[a] 00000000 00000000 00000000 10101001  0 << 8 | [0]
[b] 00000000 00000000 10101001 11100011  [a] << 8 | [1]
[c] 00000000 10101001 11100011 11001100  [b] << 8 | [2]
[d] 10101001 11100011 11001100 10011001  [c] << 8 | [3]
return d;


'C' 카테고리의 다른 글

채팅프로그램 v1.0 (윈도우기반)  (0) 2018.06.12
맥 멀티쓰레딩 기반의 채팅  (0) 2018.05.07
맥환경에서 세마포어사용법  (1) 2018.05.06