0

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?

1

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

6 Comments

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.
@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.
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.
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)
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.
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.