I want to convert decimal integers taken from an array and convert into 4-bit binary and store each of the bit into array in c#
static void Main()
{
BinaryInput a = new BinaryInput();
int[] input = { 7, 0, 0, 0, 2, 0, 4, 4, 0 };
int x;
int[] bits = new int[36];
ArrayList Actor = new ArrayList();
for (int i = 0; i < input.Length; i++)
{
x = (int)input[i];
string result = Convert.ToString(x, 2);
bits = result.PadLeft(4, '0').Select(c =>int.Parse(c.ToString())).ToArray();
Actor.Add(bits);
}
}
The ArrayList Actor consists of 9 arrays and each array consist of binary number......but i want to add each of the binary bit in a single array as an individual element of the array or arraylist {0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0}
You can write a method to get the "bits" of a number like this
private static IEnumerable<int> ToBitSequence(this int num, int size)
{
while (size > 0)
{
yield return num & 1;
size--;
num >>= 1;
}
}
Then you can use it in the following way to get your desired results.
int[] input = { 7, 0, 0, 0, 2, 0, 4, 4, 0 };
var bits = input.Reverse().SelectMany(i => i.ToBitSequence(4)).Reverse();
Console.WriteLine(string.Join(",", bits));
Results in
0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0
The reason for the two Reverse calls is because ToBitSequence will return the least significant bit first, so by feeding the number in reverse order and then reversing the results you will get the bits from most significant to least starting with the first number in your list.
This is preferable to all the parsing and formatting between char, string, and int that you're currently doing.
However if you just change Actor to List<int> and do Actor.AddRange(bits); that would also work.
Use BitArray
BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
This will give you the bits, then use
bits.Take(4).Reverse()
to get the least significant 4 bits in most-significant order first for each number.
Related
I'm looking for a way to replace every int that is greater than 9 in an array with the sum of the digits. I'm gonna demonstrate an example below.
I have this array:
int[] ints2 = new int[] { ints[0] * 2, ints[1], ints[2] * 2, ints[3], ints[4] * 2, ints[5], ints[6] * 2, ints[7], ints[8] * 2, ints[9]};
And I want to replace the first int to whatever the sum is of the two digits.
Lets say ints[0] = 9. And ints[0]*2 = 18. The sum should be 1+8 = 9.
Can I use some kind of replace method for ints? Or do you guys have any better ideas of how to deal with this issue?
I tried it like this, but obviously I'm wrong:
foreach (int number in ints)
{
int newNumberInt;
if (number > 9)
{
string newNum = number.ToString();
char[] charNum = newNum.ToCharArray();
int[] intNum = Array.ConvertAll(charNum, n => (int)Char.GetNumericValue(n));
newNumberInt = intNum[0] + intNum[1];
}
newNumberInt = number;
}
You are close. Your mistakes are an incorrect addition of digits, and failure to replace the values in the array. Here is a one line method that adds all the digits in an integer (using System.Linq):
//Adds up all the digits in a number
private static int AddDigits(int number) => number.ToString().Sum(digitCharacter => int.Parse(digitCharacter.ToString()));
For replacing the values, a foreach loop directly on the array won't work, due to changing the contents of the array during enumeration. A simple solution is to use a for loop.
for (int i = 0; i < ints.Length; i++)
{
var value = ints[i];
ints[i] = value > 9 ? AddDigits(value) : value;
}
Note: the AddDigits function I wrote only works for positive integers
I have searched in net but not getting exactly what I need.
I have a bitarray of size 15,936. I need to divide this bit array into list of bitarrays , with each bit array having 32 bits(15936/32 = 498 bitarray list).
Not able to find exactly how to divide bitarray. Please do help.
Thanks,
The first that you want 32-bit values makes this pretty easy, because you can copy it to an int[], then create one BitArray per int, passing the data by creating a single-element int array:
int[] values = new int[bigBitArray.Length / 32];
bigBitArray.CopyTo(values, 0);
var smallBitArrays = values.Select(v => new BitArray(new[] { v })).ToList();
Or more efficiently, reusing the same int[] for each iteration:
int[] values = new int[bigBitArray.Length / 32];
bigBitArray.CopyTo(values, 0);
// Reuse this on every iteration, to avoid creating more arrays than we need.
// Somewhat ugly, but more efficient.
int[] buffer = new int[1];
var smallBitArrays = values.Select(v =>
{
buffer[0] = v;
return new BitArray(buffer))
}).ToList();
If those give you the bit arrays in the opposite order to what you expect, just call Array.Reverse(values) after the CopyTo call.
It's a pity that BitArray doesn't have a constructor taking an existing array, offset and count... that would make it significantly more efficient. (As would a "slice copy" operation, of course.)
A more general purpose option would be to create an extension method precisely for that "slice copy" part:
public static BitArray CopySlice(this BitArray source, int offset, int length)
{
// Urgh: no CopyTo which only copies part of the BitArray
BitArray ret = new BitArray(length);
for (int i = 0; i < length; i++)
{
ret[i] = source[offset + i];
}
return ret;
}
Then:
var smallBitArrays = Enumerable
.Range(0, bigBitArray.Length / 32)
.Select(offset => bigBitArray.CopySlice(offset * 32, 32))
.ToList();
You can copy your bit array into an array of bytes, split that array into chunks and create new bit arrays:
const int subArraySizeBits = 32;
const int subArraySizeBytes = subArraySizeBits / 8;
byte[] bitData = new byte[myBitArray.Length / subArraySizeBytes];
myBitArray.CopyTo(bitData, 0);
List<BitArray> result = new List<BitArray>();
for (int index = 0; index < bitData.Length; index += subArraySizeBytes) {
byte[] subData = new byte[subArraySizeBytes];
Array.Copy(bitData, index * subArraySizeBytes, subData, 0, subArraySizeBytes);
result.Add(new BitArray(subData));
}
I know how to convert an integer from decimal to fixed length binary string:
int number = 3;
int toBase = 2;
int length = 8;
Convert.ToString(number, toBase).PadLeft(length, '0')
Output:
00000011
How to assign the individual elements of that binary string to either int (or bool) array, such that after the conversion the array will look like1:
int[] binary = {0, 0, 0, 0, 0, 0, 1, 1}
or
bool[] binary = {false, false, false, false, false, false, true, true};
1. Using the facilities and not trivial for loop with char to int (or bool) type conversions.
You can add some Linq to represent the string as an array:
string source = Convert.ToString(number, toBase).PadLeft(length, '0');
...
int[] binary = source.Select(c => c - '0').ToArray();
...
bool[] binary = source.Select(c => c == '1').ToArray();
Or you can compute arrays directly:
int[] binary = Enumerable
.Range(1, length)
.Select(i => number / (1 << (length - i)) % 2)
.ToArray();
bool[] binary = Enumerable
.Range(1, length)
.Select(i => number / (1 << (length - i)) % 2 == 1)
.ToArray();
If you store the string you have created, for example
string theBinaryString = Convert.ToString(number, toBase).PadLeft(length, '0');
int[] binary = new int[8];
for(int i = 0; i < 8; i++)
{
binary[i] = int.parse(theBinaryString[i].ToString());
}
Once the loop has finished you will have the array you are looking for, the ToString() is required as selecting from a string as if it was an array returns a char, which cannot be parsed into an int.
You can do it without converting the number to binary string:
var num = 123;
var bits = Enumerable.Range(0, 8).Select(i => (num >> (7-i)) & 1).ToArray();
The idea is to shift the number right sequentially by a decreasing number of positions, and mask off all bits except least significant one.
Demo.
maybe like this;
"1000110101110".ToCharArray().Select(c => c - '0').ToArray()
will give you:
int[13] { 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0 }
int[] intArray = stringNumber.ToCharArray().Select(n => Convert.ToInt32(n)).ToArray();
I have an int variable (value1).
Int value1 =95478;
I want to take each digit of value1 and insert them into an array (array1). Like this,
int[] array1 = { 9, 5, 4, 7, 8 };
No idea how this can be done. Any idea?
int[] array1 = 95478.ToString()
.Select(x => int.Parse(x.ToString()))
.ToArray();
try this
Int value1 =95478;
List<int> listInts = new List<int>();
while(value1 > 0)
{
listInts.Add(value1 % 10);
value1 = value1 / 10;
}
listInts.Reverse();
var result= listInts .ToArray();
this doesn't use strings
The most optimal solution I could come up with:
public static class Extensions {
public static int[] SplitByDigits(this int value) {
value = Math.Abs(value); // undefined behaviour for negative values, lets just skip them
// Initialize array of correct length
var intArr = new int[(int)Math.Log10(value) + 1];
for (int p = intArr.Length - 1; p >= 0; p--)
{
// Fill the array backwards with "last" digit
intArr[p] = value % 10;
// Go to "next" digit
value /= 10;
}
return intArr;
}
}
Is roughly double the speed of using a List<int> and reversing, roughly ten times faster and a tonne more memory efficient than using strings.
Just because you have a powerful computer you are not allowed to write bad code :)
I need to create a modulus check which adds leading digits, lets say 0, to a seed int. I then need to return an array of digits in the array as I need to do a calculation on each digit to return a new whole number.
my code is as follows,
var seed = 1234;
var seedString = seed.ToString();
var test = new List<int>();
for(int i = 0; i < 10 - seedString.Length; i++)
{
test.Add(0);
}
var value = seed;
for(int i = 0; i < seedString.Length; i ++)
{
test.Insert(10 - seedString.Length, value % 10);
value = value / 10;
}
is there an easier way of doing this?
If you want to convert your number to a 10-digit string, you can format the number using a Custom Numeric Format String as follows:
string result = seed.ToString("0000000000");
// result == "0000001234"
See: The "0" Custom Specifier
If you need a 10-element array consisting of the individual digits, try this:
int[] result = new int[10];
for (int value = seed, i = result.Length; value != 0; value /= 10)
{
result[--i] = value % 10;
}
// result == new int[] { 0, 0, 0, 0, 0, 0, 1, 2, 3, 4 }
See also: Fastest way to separate the digits of an int into an array in .NET?
Try this:
int myNumber = 1234;
string myStringNumber = myNumber.ToString().PadLeft(10, '0');
HTH
Another shorthand way of getting the string representation would be
int num = 1234;
num.ToString("D10");