bit / bit-operator如何控制对象状态? [英] How use bit/bit-operator to control object state?
问题描述
我想创建轻型对象数据包,以在客户端和服务器应用程序之间传递。
I want to create light object data-package to pass between client and server applications.
这是一个非常简单的任务,我只能使用1个字节,所以
每一位在一个字节将有不同的含义,
It is a so simple task, that I can control with only 1 byte, so each bit in a byte will have a different meaning,
仅使用位
0 = False
1 = True
我现在需要:
1 - Loaded from database
2 - Persisted
3 - Changed
4 - Marked to Delete
5 -
6 -
7 - Null Value
8 - Read Only
1) How do I use bit operators in Delphi to check each bit value?
2) How do I set the bit Values?
解决方案
所有帮助之后,请使用下一个设置
After all help, Ill use the next Set
TStateType = (
stLoaded = 0, // loaded from persistance
stNative = 2, // value loaded and converted to native type
stPersisted = 3, // saved
stChanged = 4, // object or member changed
stToDelete = 5, // marked to delete
stReadOnly = 6, // read only object, will not allow changes
stNull = 7 // value is null
);
TState = Set of TStateType;
对于流 - >持久性,这将是要使用的记录:
And for stream -> persistance, this will be the record to be used:
TDataPackage = record
Data: TBytes;
TypeInfo: TMetaInfo;
State: Byte;
Instance: TBuffer;
end;
谢谢,所有的答案和评论。 >
Thank you guys, for all the answers and comments.
推荐答案
我真的会为此使用一个集合。但是,我看到你真的想要一个字节。使用集合到处然后键入一个字节到最后。
I'd really use a set for this. However, I see you really want a byte. Use sets everywhere then typecast to a byte in the end.
此解决方案将需要更少的打字,支持标准的delphi运算符,并且真的不带来性能损失,因为Barry Kelly已经指出。
This solution will require much less typing, has support for standard delphi operators and really carries no performance penalty as Barry Kelly has pointed out.
procedure Test;
type
TSetValues = (
TSetValue1 = 0,
TSetValue2 = 1,
TSetValue4 = 2,
TSetValue8 = 3,
TSetValue16 = 4,
TSetValue32 = 5,
TSetValue64 = 6,
TSetValue128 = 7
);
TMySet = set of TSetValues;
var
myValue: byte;
mySet: TMySet;
begin
mySet := [TSetValue2, TSetValue16, TSetValue128];
myValue := byte(mySet);
ShowMessage(IntToStr(myValue)); // <-- shows 146
end;
这篇关于bit / bit-operator如何控制对象状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!