繁体   English   中英

将BitArray中的13位转换为有符号整数,然后将BitArray中的4位转换为整数

[英]Convert 13 bits in BitArray to signed integer then convert 4 bits in BitArray to integer

有位数组

BitArray bits = new BitArray(17);

我想把第一个13位转换为13位有符号整数,其余的按位数组4位转换为4位整数。 如何在C#中做到这一点?

假设您的位首先存储在LSB中(例如,在BitArray中最左边),则可以执行类似的操作(从本文中借用: 如何将BitArray转换为单个int? )。

int[] arr = new int[1];
bits.CopyTo(arr, 0);                 // assume that bits are stored LSB first
int first13Bits = arr[0] >> 4;       // shift off last 4 bits to leave top 13
int last4Bits = 0x0000000F & arr[0]; // mask off top 28 bits to leave bottom 4

注意, first13Bits应该被签名,但是last4Bits在这里不会被签名(因为高位被屏蔽掉了)。 如果首先位存储在MSB中,则在转换它们之前需要反转BitArray中的位(因为CopyTo似乎假定它们首先存储在LSB中)。

暂无
暂无

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

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