将布尔数组转换为字节 [英] Converting Boolean array into byte
本文介绍了将布尔数组转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好!
作为初学者,我不熟悉.NET将类型转换为其他类型的方法,因此,我恳请以下问题提供帮助.
我使用了一种将消息接收为8个字节长字节数组的设备.其字节之一表示输出状态.我已经制作了.NET类和UI来控制这些状态.唯一的问题是无法将我的布尔数组转换为Byte..
这是一个示例:
Hi all!
As beginner programmer Im not familiar with .NET methods to convert types to another so I kindly ask help with following problem.
I have empedded device which recieves messages as 8 bytes long byte array. One of its bytes represents output states. I have made .NET class and UI to control those states. Only problem is that cant cast my bool array into Byte..
Here is an example:
bool[] StatesArray = { false, true, true, false, false, false, false , false}; // States comes from MyClass properties changed by Ui component (eg. CheckBox)
//target device will read states as binary form eg. above state array: 01100000
byte[] Message = new byte[8]; //Byte array which will be The Message to be send (one index includes our states as Byte)
byte States; // byte which represents states
//States = ???? // Problem! Convert StatesArray to one byte
//Message[4] = States; //Add our states into our message
//Send the message etc..
希望你有主意:)
干杯!
Hope you got idea :)
Cheers!
推荐答案
例如:
byte encodebool(bool[] arr)
{
byte val = 0;
foreach (bool b in arr)
{
val <<= 1;
if (b) val |= 1;
}
return val;
}
您是否考虑了枚举,而不是使用布尔数组:
Rather than using an array of bools, have you considered an enum:
public enum StatusByte : byte
{
Ready = 0,
Abort = 1,
TxReady = 2,
RxReady = 3,
TxError = 4,
RxError = 5,
}
private void button1_Click(object sender, EventArgs e)
{
StatusByte sb = ReadStatus();
if ((int) (sb & StatusByte.Ready) == 1)
{
}
}
bool[] StatesArray = { false, true, true, false, false, false, false , false};
BitArray bits = new BitArray(StatesArray);
byte[] Bytes = new byte[1];
bits.CopyTo(Bytes, 0);
//Bytes[0] is your answer
这篇关于将布尔数组转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文