Reputation: 359
I want to have a rectangle in the coordinate, and use X, Y, W, H to represent that.
Is that possible to use four numbers(X: 102, Y: 45, W: 13, H: 55)to decide a unique ID, the ID should be uint256, and after that, I can just use a unique ID to retrieve (X: 102, Y: 45, W: 13, H: 55), and (X, Y, W, H) maximum number will be 10000.
Is there any formula or algorithm I can reference? Thanks.
Upvotes: 0
Views: 336
Reputation:
A simple and efficient way is to pack the four numbers represented on 16 bits (C short) as a single 64 bits integer (C union).
Upvotes: 2
Reputation: 5277
uint256
means "unsigned integer of 256 bits = 32 bytes"
This has the range from 0 to 2^256 - 1
, which is MORE than enough to store 4 ordered numbers of max size 10000.
Even if you straight up (string) concatenate (XYWH), the max number you get is: 10000100001000010000
, which is 20-digits and hence, can easily be stored in (less than) 64-bits. So, there is one (most basic and inefficient) method, and even this is well below what you want. Although it is hard to retrieve back the values.
So, you can just give 2-bytes (16 bits) to each number and then concatenate. This will (always) take 64-bit representation and it would be easy to retrieve back since you know each of (X,Y,W,H) is represented in 16-bits.
You can optimise it further, by assigning 14-bits to each value (not that you need to) and have a 56-bit representation.
Upvotes: 2