简体   繁体   English

在C#中添加多个字节数组

[英]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 01 01表示他们拥有“完全控制权”
00 00 00 00 00 00 00 02 means they have "Add Control" 00 00 00 00 00 00 00 02表示他们拥有“添加控件”
00 00 00 00 00 00 00 04 means they have "Delete Control" 00 00 00 00 00 00 00 04表示他们具有“删除控制”

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). 因此,如果用户具有“ 00 00 00 00 00 00 00 07 07”,则意味着他们拥有全部3个(据我所知)。

Now, my question is that I need to know how to get to "0x07" when creating/checking records. 现在,我的问题是创建/检查记录时我需要知道如何达到“ 0x07”。
I don't know the syntax for actually combining 0x01, 0x02 and 0x04 so that I come out with 0x07. 我不知道实际组合0x01、0x02和0x04的语法,所以我得出0x07。

You OR them together: 您或他们在一起:

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

If you want to examine the individual bits in candidate byte b : 如果要检查候选字节b的各个位:

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

The OR opeerator is what you're looking for. 您正在寻找OR操作符。

IMO, a clean way to handle it would be to use an enum: IMO,一种干净的处理方法是使用枚举:

[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);

You can also convert 8-bytes arrays into ulong array using BitConverter.ToUInt64 . 您还可以使用BitConverter.ToUInt64将8字节数组转换为ulong数组。 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. 之后,您将能够对这些ulong使用常规的按位运算,并在必要时使用BitConverter.GetBytes将结果转换回字节数组。

You might want to implement a tiny wrapper for this, if you have to deal with permissions repeatedly. 如果您必须反复处理权限,则可能要为此实现一个小型包装。

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

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