Convert C++ type int16_t to int64_t without modifying the underlying binary -


i trying generate hash code object in 3d space can found in array using binary search algorithm.

since each object in array has unique xyz location, figured use 3 values generate hash code. used following code try , generate hash code.

int64_t generatecode(int16_t x, int16_t y, int16_t z) {     int64_t hashcode = z;//set z bits.     hashcode <<= 16;//shift them 16 bits.     hashcode |= y;//set y bits.     hashcode <<= 16;//shift them 16 bits.     hashcode |= x;//set x bits. } 

now here problem can tell. consider following peace of code:

int16_t x = -1; cout << "x: " << bitset<16>(x) << endl;//prints binary value of x. int64_t y = x;//set y x. automatically cast types. cout << "y: " << bitset<64>(y) << endl;//prints binary value of y. 

the output of program follows:

x: 1111111111111111 y: 1111111111111111111111111111111111111111111111111111111111111111 

it keeps numerical value of number, changes underlying binary that. don't want modify binary can have output following:

x: 1111111111111111 y: 0000000000000000000000000000000000000000000000001111111111111111 

by doing that, can create unique hash code xyz values following:

           unused            x                 y                 z hashcode: [0000000000000000][0000000000000000][0000000000000000][0000000000000000] 

and used binary search.

convert int16_t uint16_t first, merge them uint64_t cast int64_t:

int64_t generatecode(int16_t x, int16_t y, int16_t z) {     uint64_t hashcode = static_cast<uint16_t>(z);     hashcode <<= 16;     hashcode |= static_cast<uint16_t>(y);     hashcode <<= 16;     hashcode |= static_cast<uint16_t>(x);     return static_cast<int64_t>(hashcode); } 

the int16_t/int64_t types two's complement representation (7.20.1.1 paragraph 1 of c standard requires this), converting them uint*_t of same size bit-wise no-op.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -