如何使用位标​​记 [英] How to use Bit Flags

查看:54
本文介绍了如何使用位标​​记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绝对不知道如何使用位标​​志.我有一个具有两个变量的应用程序:int buyFlag和int sellFlag.我的GUI有两列复选框.第一列代表buyFlag,第二列代表sellFlag.

如何根据复选框确定我的buyFlag和sellFlag的价值?

谢谢
-DA

I have absolutely no idea of how to use bit flags. I have an application that has two variable''s: int buyFlag and int sellFlag. My GUI has two columns of checkBoxes. The first column represents the buyFlag and the second column represents the sellFlag.

How do I determine the value of my buyFlag and sellFlag based on checkBoxes?

Thank you,
-DA

推荐答案

每个复选框都可以代表一个singel交换.每次交换将由一个值表示;例如:

Each checkbox can represent a singel exchange. Each exchange would be represented by a value; for instance:

FTSE = 1,
NYSE = 2,
DAX = 4,
CAC = 8,
DJI = 16
Sydney = 32



等等.

无论选中哪个复选框,您都将取每个复选框的值并将其加在一起.例如,如果用户选择NYSE,CAC和DJI,则您将有26个.这就是您要存储在数据库中的内容. FTSE和悉尼将是33,依此类推.

然后,您可以解释这些内容,例如,通过创建枚举并使用它来转换值来填充编辑屏幕上的复选框.

它可能看起来像:



and so on.

Whatever checkboxes get checked you take the value of each and add them together. For instance, if the user selects NYSE, CAC and DJI you will have 26. This is what you would store in your database. FTSE, and Sydney would be 33 and so on.

You can then interpret these, for instance, to populate the checkboxes on an edit screen by creating an enum and us9ing that to translate the values.

It might look like:

[Flags]
public enum Exchanges
{
    NONE = 0,
    FTSE = 1,
    NYSE = 2,
    DAX = 4
}



您可以通过以下方式决定选中哪个复选框:



You could decide which checkbox is checked with something like:

Exchanges ex = (Exchanges) value;
CheckBox1.Checked = (ex & Exchanges.FTSE) != Exchanges.NONE;


等等.有点简单,但是它会帮助您.


and so on. Bit simplistic but it''ll get you going.


我将在我的文章 ^ ].

欢迎您对位设置操作有任何疑问.

—SA
I explain bit flags in comprehensive detail in my article Enumeration Types do not Enumerate! Working around .NET and Language Limitations[^].

Any questions on bit set operations are welcome.

—SA


这篇关于如何使用位标​​记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆