union을 사용해서 4byte 인덱스 조합하기

2018. 12. 4. 11:44Programming/c++

    1. #include <iostream>
    2.  
    3. union SpawnObjectIndex
    4. {
    5. public:
    6.  
    7.     SpawnObjectIndex(unsigned short regionIndex, unsigned short localIndex)
    8.     {
    9.         region = regionIndex;
    10.         local = localIndex;
    11.     }
    12.  
    13.     unsigned int GetFullIndex() { return FullIndex; }
    14.     unsigned int GetRegionIndex() { return region; }
    15.     unsigned int GetLocalIndex() { return local; }
    16.  
    17. private:
    18.     unsigned int FullIndex;
    19.     struct  
    20.     {
    21.         unsigned short local;
    22.         unsigned short region;
    23.     };
    24. };
    25.  
    26. void idxprint(SpawnObjectIndex& idx)
    27. {
    28.     std::cout << "Full : " << idx.GetFullIndex() << std::endl;
    29.     std::cout << "Region : " << idx.GetRegionIndex() << std::endl;
    30.     std::cout << "Local : " << idx.GetLocalIndex() << std::endl;
    31.     std::cout << std::endl;
    32. }
    33.  
    34. int main()
    35. {
    36.     SpawnObjectIndex idx = SpawnObjectIndex(20);
    37.     idxprint(idx);
    38.  
    39.     SpawnObjectIndex idx2 = SpawnObjectIndex(655350);
    40.     idxprint(idx2);
    41.  
    42.     SpawnObjectIndex idx3 = SpawnObjectIndex(6553565535);
    43.     idxprint(idx3);
    44.  
    45.     return 0;
    46. }


4바이트의 unsigned int를 각각 2바이트씩 잘라서 unsigned short형의 index값을 2개 조합해서 겹치지 않는 index를 발행하기 위해 작성함.

각 키의 index범위는 unsigned short형이므로 0~65,535까지이고, Full Index의 표현 범위는 unsigned int형이므로 0~4,294,967,295까지이다.

'Programming > c++' 카테고리의 다른 글

[c++] jsoncpp 빌드 및 사용방법  (1) 2019.05.27
string split  (0) 2018.11.21
rvalue 참조 사이트  (0) 2017.02.17