Count the number of bits that are "on" in a byte [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Count the number of set bits in an integer
Best algorithm to count the number of set bits in a 32-bit integer?
That's an exam question and that is all I have - "Count the number of bits that are "on" in a byte" "On" means 1, I assume. Do I need to create a BitArray, randomly populate it and then iterate through it or is there a different way?

Using BitArray might be efficient but you could also do
byte b = ... ;
int count = Convert.ToString(b,2).ToCharArray().Count(c => c=='1');

Is this a interview question?
For a byte the fastest way would be to pre-compute an array such that a[i] = number of bits in i - the memory overhead is negligible.

Related

C# dictionary size is a prime number [duplicate]

This question already has answers here:
Why .Net dictionaries resize to prime numbers?
(3 answers)
.NET ConcurrentDictionary initial capacity set to arbitrary prime number rather than expected capacity in MSDN example documentation. Why?
(1 answer)
Closed 4 months ago.
I was reading the source code of the dictionary and came across the resize method. I saw the formula temp = (currentSize * 2), currentSize = GetNextPrimalNumber(temp). Why we must to set primal number as a dictionary size? https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,440
Can somebody explain why we should use primal numbers as a size of dictionary? Thanks a lot !

How to convert float value to byte in c# [duplicate]

This question already has answers here:
How do I convert an array of floats to a byte[] and back?
(4 answers)
Closed 1 year ago.
I want to convert 794.328247 value to byte.
I used Convert.ToByte(794.328247) but it showing following error,
Error : - Value was either too large or too small for an unsigned byte.
So anyone can help me to resolve this issue.
Thanks.
You probably want Bitconverter.GetBytes
byte[ ] byteArray = BitConverter.GetBytes( 794.328247);
Note that this produce an array of bytes since a float is 32bit, so it needs 4 bytes to store it. Do the reverse with ToSingle.
The alternative is to truncate the float: var b = (byte) 794.328247;, but this is usually not a good idea since a byte has a far smaller range of values that a float. In some cases you might need to first normalize the input value to some range of values before truncating. I.e. you would remap values from say 750-800 to the 0-255 range.

If integer look like this `010` is first 0 consider integer? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
There was misunderstanding about this int number = 010, What I am saying is
first 0 is not integer due to c# has no leading zero so 010 will be 10
however one of stackoverflow user saying
first 0 in 010 is integer
so could anyone help to explain in details why first 0 in 010 is integer even though it has no value or it doesn't represent any mathematical integer !
thanks in advance
When you are writing integer literals, leading zeros don't mean anything.
var a = 10;
var b = 010;
a == b // true
It's not that the "first 0 is not [an] integer", it's that the leading 0 is ignored, because it doesn't contribute any information to the value of the number.
The same is with binary notation - leading zeros do not increase the information of the number (except for maybe the storage size of the value, but that's meta-information).
If you're dealing with strings, that's a whole different ballgame, as "010" has a different character array than "10", even if they parse to the same integer value.
var c = "010"
var d = "10"
c == d // false
int.Parse(c) == int.Parse(d) // true
Ok so obviously 0 is an integer and you can do the math on a 0. 0*1 = 0 for example. When looking at what your computer sees from an integer standpoint you'll notice that 010 and 10 both have the same binary representation. So that begs the question, why is 0 being ignored? Remember that computers understand instructions, one... at... a... time. Meaning that when it first reads through that integer, even with math, it starts at the first character and goes through. The only other difference is strings or other data types that may make better use of that 0.
Binary Representation of 10
1010
Binary Representation of 010
1010
Now since we recognize that computers read one instruction at a time, if it is given a 0 (Which has a binary representation of 0) what happens when that instruction has any math completed on it? Nothing is what happens. 0*100=0 or 0/2=0 the difference being addition or subtraction which takes your integer into positive or negative value. 0+100=100 now if you look at the instructions it again starts with the 0 and then it's cleaned out leaving you with the binary representation of whatever had some calculation.

Why do I get System.OverflowException when init array [duplicate]

This question already has answers here:
What is the Maximum Size that an Array can hold?
(6 answers)
Closed 4 years ago.
byte[] buffer2 = new byte[4294743227]; // string with System.OverflowException
The number 4294743227 is uint.
Why do i get exception?
According to this question, the maximum size of an array is System.Int32.MaxValue, which is 2,147,483,647.
See also the documentation on System.Array:
By default, the maximum size of an Array is 2 gigabytes (GB). In a
64-bit environment, you can avoid the size restriction by setting the
enabled attribute of the gcAllowVeryLargeObjects configuration element
to true in the run-time environment. However, the array will still be
limited to a total of 4 billion elements, and to a maximum index of
0X7FEFFFFF in any given dimension (0X7FFFFFC7 for byte arrays and
arrays of single-byte structures).

How to convert double value to two byte array in c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am developing a windows forms application. I have a double value 1.5.That value I need to convert into a two byte array. But when I am converting using BitConverter.GetBytes, getting 8 bytes of data. Please refer my code below.
double d = 1.5;
byte[] array = BitConverter.GetBytes(d);
Double is 8 byte value, so if you have an arbitrary double there's no hope for you; however, if you have some restrictions, e.g. the value is in the [0..100] range and has at most 2 digits after the decimal point, you can encode it:
// presuming source in [0..100] with at most 2 digit after decimal point
double source = 1.5;
// short is 2 byte value
short encoded = (short) (source * 100 + 0.5);
byte[] array = BitConvertor.GetBytes(encoded);
// decode back to double
double decoded = encoded / 100.0;
A double is a 64 bit value that just so happens to be 8 bytes. There's nothing that can be done about this.
A double is 8 bytes in length, so unless you want a specific sub-array out of the 8 you're getting (you probably don't), then this is the wrong way to go about it.
You can cast your variable to a single-precision float. That will of course lose some precision, but you will get 4 bytes instead of 8.
If this is still unacceptable, you need to have an implementation of a half-precision float, which sadly doesn't come out-of-the-box with .NET.
I found an implementation here:
http://sourceforge.net/p/csharp-half/code/HEAD/tree/System.Half
You can use it like this:
var half = (Half)yourDouble;
var bytes = Half.GetBytes(half); // 2 bytes

Categories