I am working in an app that connects to a Siemens PLC using LibnoDave library. I am getting a Dword value that I convert it into an INT value, but now I need to convert this INT value into a BIT array. For example, I get as a INT value the number 62000 that in binary is 1111001000110000. I need that value. How can this be done?
2 Answers
If you want to represent uint in binary, try using Convert class:
uint source = 62000;
string result = Convert.ToString(source, 2);
Console.WriteLine(result);
Outcome
1111001000110000
If you want System.Collections.BitArray instance:
using System.Collections;
using System.Linq;
...
uint source = 62000;
BitArray array = new BitArray(BitConverter.IsLittleEndian
? BitConverter.GetBytes(source)
: BitConverter.GetBytes(source).Reverse().ToArray());
// Test
string result = string
.Concat(array
.OfType<bool>()
.Reverse()
.Select(item => item ? 1 : 0))
.TrimStart('0');
Console.WriteLine(result);
Outcome
1111001000110000
6 Comments
Evk
Is
Convert.ToString always treat number as big endian? Side note: TrimStart('0') seems to be unnecesasry. If you for example use uint source = 0 - result will be empty string, while expected result (I think) is string with 16 zeroes.Dmitrii Bychenko
@Evk: Thank you! I agree with endians check; but since the
result just demonstrates array contains correct data (for a single 62000 test) let me keep TrimStart as it is.Evk
But that's because you use
uint. Since OP says that 62000 is represented as 2 bytes - you have to use ushort. INT he uses in question can mean anything, because as I understand it's not C# int. And with ushort you can remove TrimStart. Your endianess check is also a bit strange, because you reverse once if BitConverter is not little endian, and then you reverse once again when working with BitArray. So you need to reverse if BitConverter is little endian and remove Reverse() when doing Concat.Dmitrii Bychenko
If I understand the question right, it's about
DWORD msdn.microsoft.com/en-us/library/cc230318.aspx "32-bit unsigned integer", that's why I've put uint (UInt32)Evk
Well he converts DWORD into some INT value, and that INT value he needs to convert to bit array (maybe INT is msdn.microsoft.com/en-us/library/cc230334.aspx in which case we are both wrong). Anyway, OP indeed can decide himself what he means.
|