1

Is there a way to show the representation of an int in bits in c#?

i.e.

1  = 00001
20 = 10100

etc.

I have tried using BitConverter with no luck. This should be simple, but I can't find a solution!

2
  • This question: stackoverflow.com/questions/6758196/… seems to have a few solutions to your question. Commented Aug 14, 2013 at 1:29
  • Thanks @EdgySwingsetAcid - knew this had to be on SO somewhere, just couldn't find it! Cue the votes to close... Commented Aug 14, 2013 at 1:31

3 Answers 3

7

Convert.ToString(value, base)

Converts the value of a 32-bit signed integer to its equivalent string representation in a specified base. Specify 2 for the base.

Sign up to request clarification or add additional context in comments.

Comments

2

Here's a one-liner using linq:

var myint = 20;
var bytes = Enumerable.Range(0, 32).Select(b => (myint >> b) & 1);
// { 0, 0, 1, 0, 1, 0 ... }

Of course this is in reverse order, to swap it around just use:

var myint = 20;
var bytes = Enumerable.Range(0, 32).Select(b => (myint >> (31 - b)) & 1);
// { ..., 0, 1, 0, 1, 0, 0 }

1 Comment

That's smart! Thank you. I will accept the Convert.ToString() answer since it seems to be a more standard method. But I like this answer a lot!
1

You could also look at using a BitArray.

var array = new BitArray(BitConverter.GetBytes(1));

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.