Botez Adrian
Botez Adrian

Reputation: 27

Converting Dword into Bit array in C#

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?

Upvotes: 0

Views: 1893

Answers (2)

Botez Adrian
Botez Adrian

Reputation: 27

The question is that in that DWORD I only need the second word. For exampel if I receive 11111111111111110000000000000000 , I only need the 1111111111111111 of this Dword.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

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 

Upvotes: 2

Related Questions