James P. Wright
James P. Wright

Reputation: 9131

Adding multiple byte arrays in c#

I'm working on a legacy system that uses byte arrays for permission levels.
Example:
00 00 00 00 00 00 00 01 means they have "Full Control"
00 00 00 00 00 00 00 02 means they have "Add Control"
00 00 00 00 00 00 00 04 means they have "Delete Control"

So, if a User has "00 00 00 00 00 00 00 07" that means they have all 3 (as far as it has been explained to me).

Now, my question is that I need to know how to get to "0x07" when creating/checking records.
I don't know the syntax for actually combining 0x01, 0x02 and 0x04 so that I come out with 0x07.

Upvotes: 1

Views: 426

Answers (3)

Nick Hill
Nick Hill

Reputation: 4927

You can also convert 8-bytes arrays into ulong array using BitConverter.ToUInt64. After that you'll be able to use regular bitwise operations on those ulongs and convert the result back to byte array using BitConverter.GetBytes if necessary.

You might want to implement a tiny wrapper for this, if you have to deal with permissions repeatedly.

Upvotes: 0

itsme86
itsme86

Reputation: 19526

The OR opeerator is what you're looking for.

IMO, a clean way to handle it would be to use an enum:

[Flags]
public enum Permisions
{
    FullControl = 0x1,
    AddControl = 0x2,
    DeleteControl = 0x4
}

Then, in your code you can do things like:

Permissions userPermissions = Permissions.AddControl | Permissions.DeleteControl;
bool canDelete = userPermissions.HasFlag(Permissions.DeleteControl);

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180908

You OR them together:

0x01 | 0x02 | 0x04 == 0x07

If you want to examine the individual bits in candidate byte b:

Full Control   == b & 0x01
Add Control    == b & 0x02
Delete Control == b & 0x04

Upvotes: 1

Related Questions