简体   繁体   English

从long编码/解码整数

[英]Encoding/Decoding integers from long

I have following structs: 我有以下结构:

struct ID
{
   UINT id;         // range from 0 to 10 000 000
   UINT residentNb; // range same as for id (above).
};

struct FullID
{
   ID myID;
   ID systemID;
};

Now, UINT id in above struct ID have specified range in my system. 现在,以上结构ID UINT id ID已在我的系统中指定了范围。 This range is always from min 0 to max 10 000 000. I would like to transform struct FullID to one number, UINT64 for example, and be able to encode/decode data from it - myID and systemID (like in above struct). 该范围是总是从最小0至最大10 000 000。我想结构变换FullID到一个号码, UINT64例如,并且能够编码从它/解码数据- myIDsystemID (如在以上结构)。 Is it possible, and what is the best way to do it? 有可能吗,最好的方法是什么? Of course 10 000 000 limit can be rounded to some higher value if this is necessary for proper conversions. 当然,如果需要正确转换,则可以将1000000个限制取整为更高的值。

Example

UINT64 encodedID;

(...)

FullID fullID = Decode(encodedID);

(...)

encodedID = Encode(fullID);

I suggest using a union to avoid strict aliasing optimization bugs (google for strict aliasing if you do not know what it is). 我建议使用联合来避免严格的别名优化错误(如果您不知道它是什么,请使用Google严格的别名)。

And then, just use bitmasks and bitshifts to encode/decode. 然后,只需使用位掩码和位移位进行编码/解码。 Stay away from bitfields, they are not easy to work with if you want portable code. 远离位域,如果要使用可移植代码,则不容易使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM