Get an array of bits that represent an int in c#

試著忘記壹切 提交于 2020-07-09 16:55:48

问题


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!


回答1:


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.




回答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 }



回答3:


You could also look at using a BitArray.

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


来源:https://stackoverflow.com/questions/18221769/get-an-array-of-bits-that-represent-an-int-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!