开发者

Saving a vector as a single number?

I was wondering if it would be possible to get a vector with an X and a Y value as a single number, knowing that both X and Y can range from -65000 to +65000.

Is 开发者_运维问答this possible in any way?

Code examples on how to convert from this kind of number and to it would be nice.


Store it in a ulong:

ulong rslt = (uint)x;
rslt = rslt << 32;
rslt |= ((uint)y);

To get it out:

int x = (int)(rslt >> 32);
int y = (int)(rslt & 0xFFFFFFFF);


Assuming X and Y are both integer values and there is no overflow (32bit values is not enough) you can use e.g. (pseudocode)

V = fromXY(X, Y) = (y+65000)*130001+(x+65000)
(X,Y) = toXY(V) = (V%130001-65000,V/130001-65000)    // <= / is integer division

(130001 is the number of distinct values for X or Y)


To combine:

var limit = 65000;
var x = 1;
var y = 2;
var single = x * (limit + 1) + y;

And then:

y = single % (limit + 1);
x = single - y / (limit + 1);

See it in action.

Of course, you have to assume that the maximum value for single fits within the size of the data type that stores it (which in this case it does).


the union does what you want very easily. See also: http://www.cplusplus.com/doc/tutorial/other_data_types/

typedef long int64;
typedef int int32;

union {
    struct { int32 a, b; };
    int64 a_and_b;
} stacker;

int main ()
{
    stacker.a = -1000;
    stacker.b = 2000;
    cout << stacker.a << ", " << stacker.b << endl;
    cout << stacker.a_and_b << endl;
}    

this will output:
-1000, 2000 <-- a and b read as two int32
8594229558296 <-- a and b interprested as a single int64

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜