开发者

How to Convert an Enum to an array of Bytes?

开发者 https://www.devze.com 2023-04-03 09:32 出处:网络
I have an enum as below: [Flags] public enum AggregationLevel { /// <summary> /// 00000001 /// </summary>

I have an enum as below:

[Flags]
public enum AggregationLevel
{
    /// <summary>
    /// 00000001
    /// </summary>
    Department = 1,

    /// <summary>
    /// 00000010
    /// </summary>
    Gbu = 2,

    /// <summary>
    /// 00000100
    /// </summary>
    Division = 4,

    /// <summary>
    /// 00001000
    /// </summary>
    Region = 8,

    /开发者_JAVA技巧// <summary>
    /// 00010000
    /// </summary>
    Market = 16,

    /// <summary>
    /// 00100000
    /// </summary>
    Cluster = 32,

    /// <summary>
    /// 01000000
    /// </summary>
    Store = 64
}

Then I have a stored procedure parameter which requires a varbinary (array of bytes).

I have an enum instance which should be passed to it:

AggregationLevel thisLevel = AggregationLevel.Department & AggregationLevel.Division;

Then, the value should be passed to this stored procedure:

var parameter = new SqlParameter("@pBitMask", SqlDbType.VarBinary)

parameter = ?

How to convert my 'thisLevel' enum to an array of bytes so that it can be assigned to this sql parameter?

Thanks,


A few things..

1) You need to use OR rather than AND:

AggregationLevel thisLevel = AggregrationLevel.Department | AggregationLevel.Division;

2) You can use this sequence so you don't have to remember powers of 2 in decimal:

0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100 ...

3) Finally, varbinary is not what you want. Look at integer or bigint. Enums are stored as ints or longs, and you are limited to the number of bits in an int or a long. If you do want to store in a varbinary, you'll need to serialise a value to a string of bytes, will will vary depending on whether you want big-endian, how many bytes should be used for storage - maybe it's even variable, etc. More information needed.

Two options for #3:

A. If it's just you/code under your control, don't use varbinary, use int or bigint (depending on number of bits required). Better still (potentially), use bit fields instead, if you're going to query on them

B. If it's not, the DBA or app provider will be able to specify how they want their varbinary populated

Hope that helps.


Use int in your DB and store as int value:

AggregationLevel thisLevel = AggregationLevel.Department | AggregationLevel.Division;

int val = (int)thisLevel;

AggregationLevel lvlUpd = (AggregationLevel)val;


You don't need to store it as an "array of bytes", a combined value fits comfortably in a single integer.

0

精彩评论

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