C# How to Remove leading 0's from 32bit int - c#

I ran into this question when watching the twit.tv show coding 101 (episode 2). The code was pre written, but we were asked to change it in order to print out all the values of the while loop that converted an integer to a binary number.
I was able to print out everything with a simple "Console.WriteLine(number);" line. When doing so, it returns all the values for the 32-bit int 0's included.
My question, is there a way to trim or remove all the extra 0's in the division of the loop (not in the final binary number) so they are not printed? Here is the code of the program:
public static string ConvertIntToBinary(int number)
{
int bits = (sizeof(int) * 16); //32bits
char[] result = new char[bits]; //Array to hold the binary numbers http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
while (bits > 0)
{
bits = bits - 1;
int remainder = number % 2; //% called mod or modulo which computes the remainder after dividing http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
if (remainder == 1) //If remainder is 1, store it as 1
result[bits] = '1';
else
result[bits] = '0'; //Otherwise store it as 0
number = number / 2; //Take the original number, divide it by 2
Console.WriteLine(number);
}
return new string(result).TrimStart('0'); //return the result as a string ,removing extra 0's
}

Terminate the loop when number reaches 0. At that point there are no more non-zero bits to pull off:
public static string ConvertIntToBinary(uint value)
{
int totalbits = sizeof(int) * 8;
char[] result = new char[totalbits];
int bits = totalbits;
uint number = value;
while (bits > 0)
{
bits--;
uint remainder = number % 2;
result[bits] = remainder == 0 ? '0' : '1';
number /= 2;
if (number == 0)
break;
}
return new string(result, bits, totalbits - bits);
}
I fixed an error in the code: there are 8 bits in a byte, and not 16 as per your code. I also simplified a few parts of the code. I used a conditional expression which is more concise than the if. And I introduced another local variable to hold the working value to avoid modifying the actual parameter. This is generally good practise that makes debugging easier. I also used uint for the input parameter since the entire approach depends on the value being positive.
Note that the termination is inside the loop rather than in the while test. If you test for number equal to 0 in the while condition then you will end up returning the empty string for an input of 0.

Just ignore all the Zero bits as you loop until you hit a '1' bit.
This works with negative numbers as well.
public static string ConvertIntToBinary(int number)
{
if (number == 0) return "0";
var bits = (sizeof(int) * 8); // 8bits per byte
var sb = new StringBuilder();
var print = false;
var mask = (uint)(1 << bits - 1);
while (bits-->0)
{
var bit = (number & mask) == mask;
if (bit) print = true;
if (print) sb.Append(bit ? '1' : '0');
mask = mask >> 1;
}
return sb.ToString();
}

Related

C# exponential format: force the first digit to be zero

I have no problem converting a double to such a string: 7.8746137240E-008
I don't know how to force the first digit to always be zero: 0.7874613724E-007
How to achieve that using a custom string format in C#?
Maybe do it yourself ;)
double foo = 7.8746137240E-008;
var numOfDigits = foo == 0 ? 0 : (int)Math.Ceiling(Math.Log10(Math.Abs(foo)));
string formatString = string.Format("{0:0.000000}E{1:+000;-000;+000}", foo / Math.Pow(10, numOfDigits), numOfDigits);
I found a simple solution:
value.ToString("\\0.0000000000E+000;-\\0.0000000000E+000")
You can do this by formatting with standard exponential notation followed by some post-processing:
public static string FormatNumberExpZero(double value, IFormatProvider format = null) {
if (!double.IsFinite(value)) // Infinity and NaN
return value.ToString(format);
// Format the number to a temporary buffer.
// "E10" means exponential notation with 10 decimal places.
Span<char> buffer = stackalloc char[24];
value.TryFormat(buffer, out int charCount, "E10", format);
// Don't touch any negative sign.
Span<char> bufferNoSign = (buffer[0] == '-') ? buffer.Slice(1) : buffer;
// Move everything after '.' one character forward to make space for the additional zero.
bufferNoSign.Slice(2, charCount - 2).CopyTo(bufferNoSign.Slice(3));
charCount++;
// Change 'X.' to '0.X'
bufferNoSign[2] = bufferNoSign[0];
bufferNoSign[1] = '.';
bufferNoSign[0] = '0';
// Read the exponent from the buffer.
Span<char> expChars = buffer.Slice(charCount - 4, 4);
int exponent = (expChars[1] - '0') * 100 + (expChars[2] - '0') * 10 + expChars[3] - '0';
if (expChars[0] == '-')
exponent = -exponent;
// Add 1 to the exponent to compensate.
exponent++;
// Write the new exponent back.
expChars[0] = (exponent < 0) ? '-' : '+';
int expAbs = (exponent < 0) ? -exponent : exponent;
int expDigit1 = expAbs / 100;
int expDigit2 = (expAbs - expDigit1 * 100) / 10;
int expDigit3 = expAbs - expDigit1 * 100 - expDigit2 * 10;
Console.WriteLine((expDigit1, expDigit2, expDigit3));
expChars[1] = (char)(expDigit1 + '0');
expChars[2] = (char)(expDigit2 + '0');
expChars[3] = (char)(expDigit3 + '0');
// Create the string.
return new string(buffer.Slice(0, charCount));
}
This solution is better than the one by #MarkSouls because it does not suffer from floating-point inaccuracy and/or overflow to infinity of doing value * 10. This requires .NET Standard 2.1 and so doesn't work with .NET Framework, though it can be modified to work with it (at the cost of allocating an additional string and char array).
I know no fancy way of achieving what you want but you can do it by writing your own function.
public static class Extender
{
public static string MyToString(this double value)
{
string s = (value * 10).ToString("E");
s = s.Replace(".", "");
return "0." + s;
}
}
It's just modifying exponential count and moving . front then adding 0.
public static void Main(string[] args)
{
Console.WriteLine(1d.MyToString());
Console.WriteLine(3.14159.MyToString());
Console.WriteLine(0.0033.MyToString());
Console.WriteLine(999414128.0.MyToString());
}
/* Output
0.1000000E+001
0.3141590E+001
0.3300000E-002
0.9994141E+009
*/
Not super cool code but it works, though I didn't check edge cases.
I wonder if there's more formal way to do it.

Algorithm to get which values make sum of a given number from array

I don't know to search or google it so I ask it here.
I have an array of integers with fixed size and exactly with this logic.
sample [1,2,4,8,16,32]
Now I am given a number for example 26. And I shall find the numbers whose sum will make this number, in this case is [2,8,16]
for a number of 20 it will be [4,16]
for 40 it is [8,32]
and for 63 it is all of these numbers [1,2,4,8,16,32]
What is the proper algorithm for that?
I know strictly that there is always this continuation that the number is double of the previous value.
as well as only the numbers from the given array will sum up to the given number and each number will be used only for once or none
If it will be in C# method that takes array of ints and an int value and returns the array of ints that contains the ints that sum up this number from the given array will be preferred.
Thank you
As you can see, the number are base-2, which means you can easily use shift.
You could try this:
private IEnumerable<int> FindBits(int value)
{
// check for bits.
for (int i = 0; i < 32; i++)
{
// shift 1 by i
var bitVal = 1 << i; // you could use (int)Math.Pow(2, i); instead
// check if the value contains that bit.
if ((value & bitVal) == bitVal)
// yep, it did.
yield return bitVal;
}
}
This method will check what bits are set and return them as an ienumerable. (which can be converted to an array of list)
Usage:
// find the bits.
var res = FindBits(40).ToArray();
// format it using the string.join
var str = $"[{string.Join(",", res)}]";
// present the results
Console.WriteLine(str);
Results in [8,32]
Extra info:
counter
00000001 = 1 = 1 << 0
00000010 = 2 = 1 << 1
00000100 = 4 = 1 << 2
00001000 = 8 = 1 << 3
00010000 = 16 = 1 << 4
00100000 = 32 = 1 << 5
01000000 = 64 = 1 << 6
10000000 = 128 = 1 << 7
Instead of writing all combinations you make a for loop which does the counter.
Some extra non-sense:
If you like lambda's, you could replace the FindBits with this:
private Func<int, IEnumerable<int>> FindBits = (int value) => Enumerable
.Range(0, 31)
.Select(i => 2 << i).Where(i => (value & i) == i);
But it's better to keep it simpel/readable.
First you should notice that
( 1 2 4 8 16 ... ) = (2^0 2^1 2^2 2^3 2^4 ... )
And that this is the same as finding a binary encoding for a decimal number. What you are looking for is an algorithm to transform a decimal or base 10 number to a binary or base 2 number.
The algorithm is pretty simple:
public List<int> dec_to_bin(int num)
{
List<int> return_list = new List<int>();
int index = 0;
int remainder = num;
int bit = 0;
while (remainder > 0)
{
bit = remainder % 2;
if (bit == 1 )
{
return_list.Add((int)Math.Pow(2, index));
}
remainder = remainder / 2;
index = index + 1;
}
return return_list;
}
There is a better way however that just uses the underlying encoding of the number which is already binary.
public List<int> dec_to_bin(int num)
{
List<int> return_list = new List<int>();
int value = 1;
while( value < num )
{
if( (value & num) == value )
{
return_list.Add(value);
}
value = value * 2;
}
return return_list;
}
Another way to state your requirement is "What are the unique powers of 2 that sum to a given integer?" Since computers work with powers of 2 natively, there are built-in goodies in most languages to do this very succinctly.
As a bonus, you can use existing .Net types and methods to eliminate the need to write your own loops.
Here's one approach:
IEnumerable<int> GetCompositePowersOf2(int input) =>
//convert to enumerable of bools, one for each bit in the
//input value (true=1, false=0)
new BitArray(new[] { input }).Cast<bool>()
// get power of 2 corresponding to the position in the enumerable
// for each true value, gets 0 for false values.
.Select((isOne, pos) => isOne ? (1 << pos) : 0)
//filter out the 0 values
.Where(pow => pow > 0);
I don't quite get the " takes array of ints " part, since this creation of sums only works with numbers that are the power of 2.
private int[] count (int num)
{
int factor = 0;
List<int> facts = new List<int>();
while (num > 0)
{
int counter = 0;
int div = num;
int remainder = 0;
while (remainder == 0)
{
remainder = div % 2;
div = div / 2;
counter++;
}
factor = 1;
for (int i = 1; i < counter; i++)
factor *= 2;
num = num - factor;
facts.Add(factor);
}
return (facts.ToArray());
}

How to divide number on separate digits to add values to each other

can you help me figure out how to calculate this way, for example I have some integer:
first I need condition
if (x < 10) to avoid asked calculation for single numbers
now if number contains more then 1 digit need to calculate it second way, for example, I got 134 how to separate it to calculate it this way 1 + 3 + 4 to attach this value 8 to variable.
So question is how to separate numbers
try
int num = 12345;
// holder temporarily holds the last digit of the number
int holder = 0;
int sum = 0;
while (num>0)
{
holder = num%10;
num = num/10;
sum += holder;
}
//sum would now hold the sum of each digit
This isn't C# in particular, but you can loop over your number then get it digit by digit.
// -- c
int num = 134;
int sum = 0;
while(num != 0) {
ones_digit = num % 10;
sum += ones_digit;
num = (num - ones_digit) / 10;
}
printf("sum: %d", sum);
On higher-level languages like javascript or python, accessing the digits can also be done by converting the integer to a string, then casting each char to an int type.
// -- javascript
var num = 134;
var digits = num.toString().split("").map(parseInt);
console.log(digits);

Efficient multiplication [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have written some code to multiply really long numbers. Was wondering if there are more efficient ways to do this?
Here's how I've done it for now. Basically implemented the typical 'Long multiplication' technique.
internal enum Digit
{
Zero = 0,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine
}
public class NumbersWhiz
{
public string Add(string Augend, string Addend)
{
string longerNum = (Augend.Length > Addend.Length == true) ? Augend : Addend;
string shorterNum = (Addend.Length < Augend.Length == true) ? Addend : Augend;
int longerLen = (Augend.Length > Addend.Length == true) ? Augend.Length : Addend.Length;
int shorterLen = (Addend.Length < Augend.Length == true) ? Addend.Length : Augend.Length;
//Pad the shorter number initially with zeros to match length of longer number
int deltaLen = longerLen - shorterLen;
string numTwoZeroed = new String('0', deltaLen);
string numTwo = numTwoZeroed.Insert(deltaLen, shorterNum);
string numOne = longerNum;
string result = new String('0', longerLen);
StringBuilder resultBuilder = new StringBuilder(result);
bool carryForward = false;
for (int index = longerLen; index > 0; index--)
{
int augend = Convert.ToInt32(numOne.Substring(index - 1, 1));
int addend = Convert.ToInt32(numTwo.Substring(index - 1, 1));
int sum = (carryForward == true) ? 1 : 0;
sum = sum + augend + addend;
carryForward = ((sum > 9) == true) ? true : false;
int reminder = sum % 10;
resultBuilder[index - 1] = Convert.ToChar(reminder.ToString());
}
if(carryForward)
resultBuilder.Insert(0, '1');
return resultBuilder.ToString();
}
public string Multiply(string Multiplicand, string Multiplier)
{
int resultLen = Multiplicand.Length + Multiplier.Length;
string totalSum = new String('0', resultLen);
for (int index = Multiplier.Length; index > 0; index--)
{
int multiplierDigit = Convert.ToInt32(Multiplier.Substring(index - 1, 1));
string product = Multiply(Multiplicand, (Digit)multiplierDigit);
product += new String('0', Multiplier.Length - index);
totalSum = Add(totalSum, product);
}
return totalSum;
}
string Multiply(string Multiplicand, Digit MultiplierDigit)
{
int multiplier = (int)MultiplierDigit;
if (multiplier == 0)
return "0";
int carry = 0;
bool carryForward = false;
int len = Multiplicand.Length;
int productLen = len + 1;
string result = new String('0', productLen);
StringBuilder resultBuilder = new StringBuilder(result);
for (int index = len; index > 0; index--)
{
int multiplicandDigit = Convert.ToInt32(Multiplicand.Substring(index - 1, 1));
int product = (multiplicandDigit * multiplier) + carry;
carryForward = ((product > 9) == true) ? true : false;
int reminder = product % 10;
carry = (product - reminder) / 10;
resultBuilder[index] = Convert.ToChar(reminder.ToString());
}
if (carryForward)
resultBuilder[0] = Convert.ToChar(carry.ToString());
return resultBuilder.ToString();
}
}
Yes--this is a digit-by-digit operation.
You have a couple of obvious options for doing things faster. One is a binary operation, where you treat one of the numbers as the sum of powers of two, and the result also as the sum of the partial results you get by multiplying by those powers of two.
For example, let's do 17 x 11 (which should give us 181, I believe).
So, let's think of 17 as powers of 2. It's 20 + 24 (i.e., 1 + 16). So we can take 11 * 1 + 11 * 16. We can do each of these multiplications with a shift, so it's 11<<0 + 11<<4.
Another way to look at things (that leads to a somewhat different way of doing things) is useful for large numbers. For the sake of argument, let's assume you can only do 4-bit operations. In this case, you can think of each number in 4-bit pieces and use the distributive property of multiplication to get a result--that is, we take each large number, and break it up into the sum of numbers, each of which represents a "slice" of the bits that make up the whole number. For example, consider something like 0x1234 * 0x4321, and (for the same of simplicity) we'll assume we're going to multiply them with a CPU that can multiply two 8-bit operands to produce a 16-bit result. So, we break each of those up into 8-bit slices:
(0x1200 + 0x34) * (0x4300 + 0x21)
Then we can use the distributive property:
0x1200 * 0x4300 + 0x1200 * 0x21 + 0x34 * 0x4300 + 0x34 * 0x21
Each of these (obviously enough) has only 8 significant bits, so we can carry out each of the operations on our 8-bit CPU. Then you basically just have to take the 4 intermediate results and add them all together. Any reasonable CPU will have a carry bit and an add-with-carry instruction you can use to handle this multiple precision operation.
Although I've shown it with 8-bit operations here, I think it's pretty obvious how this extends to (for example) 256-bit operands on a 32-bit or 64-bit CPU.
Well, yes. There are more advanced multiplication methods.
A quick and easy way to speed up your algorithm a bit is to move from base-10 (aka decimal places) into a number system which is more appropriate for computers. working with 32 bit or 64 bit integers in base-2 will be much faster. You do more work per calculation and also get rid of all the modulo calculations.
Beyond that you could replace the (trivial) multiplication algorithm by something better. If your numbers start to get really large you can get huge speedups by moving into a different complexity region. Your algorithm has complexity O(n*m) where n and m are the number of digits of the two factors.
The Fast Fourier Transform can be used to do huge number multiplications much faster in O(n log n). Worth mentioning is the Number Theoretic Transform which is even more suited for this task.
There is a lot to learn and explore in the topic of large integer arithmetic. If you however just want to multiply numbers and don't care about how it's done I suggest to just use a tested and fast bignum library.

How to convert integer to binary string in C#?

I'm writing a number converter. How can I convert a integer to a binary string in C# WITHOUT using built-in functions (Convert.ToString does different things based on the value given)?
Binary -> Sign magnitude
Binary -> One's complement
Binary > Two's complement
Simple soution:
IntToBinValue = Convert.ToString(6, 2);
Almost all computers today use two's complement representation internally, so if you do a straightforward conversion like this, you'll get the two's complement string:
public string Convert(int x) {
char[] bits = new char[32];
int i = 0;
while (x != 0) {
bits[i++] = (x & 1) == 1 ? '1' : '0';
x >>= 1;
}
Array.Reverse(bits, 0, i);
return new string(bits);
}
That's your basis for the remaining two conversions. For sign-magnitude, simply extract the sign beforehand and convert the absolute value:
byte sign;
if (x < 0) {
sign = '1';
x = -x;
} else {
sign = '0';
}
string magnitude = Convert(x);
For one's complement, subtract one if the number is negative:
if (x < 0)
x--;
string onec = Convert(x);
At least part of the answer is to use decimal.GetBits(someValue) to convert the decimal to its binary representation.
BitConverter.GetBytes can be used, in turn, on the elements returned from decimal.GetBits() to convert integers into bytes.
You may find the decimal.GetBits() documentation useful.
I'm not sure how to go from bytes to decimal, though.
Update: Based on Author's update:
BitConverter contains methods for converting numbers to bytes, which is convenient for getting the binary representation. The GetBytes() and ToInt32() methods are convenient for conversions in each direction. The ToString() overloads are convenient for creating a hexadecimal string representation if you would find that easier to interpret as 1's and 0's.
var a = Convert.ToString(4, 2).PadLeft(8, '0');
Here's mine:
(The upper part convert 32-char binary string to 32-bit integer, the lower part convert 32-bit integer back to 32-char binary string).
Hope this helps.
string binaryString = "011100100111001001110011";
int G = 0;
for (int i = 0; i < binaryString.Length; i++)
G += (int)((binaryString[binaryString.Length - (i + 1)] & 1) << (i % 32));
Console.WriteLine(G); //‭7500403‬
binaryString = string.Empty;
for (int i = 31; i >= 0; i--)
{
binaryString += (char)(((G & (1 << (i % 32))) >> (i % 32)) | 48);
}
Console.WriteLine(binaryString); //00000000011100100111001001110011
You can construct the representations digit by digit from first principles.
Not sure what built-in functions you don't want to use, but presumably you can construct a string character by character?
Start with the highest power of two greater than the number.
Push a "1" into your string.
Subtract that power of two from your number.
Take the next-lowest power of two. If you've reached one-half, stop. You're done.
If the number that's left is greater than this power of two, go back to step 2. If not, push a "0" into the string and go back to step 4.
For one's complement and two's complement, calculate those with an additional step.
Or is this way too basic for what you need?
This is an unsafe implementation:
private static unsafe byte[] GetDecimalBytes(decimal d)
{
byte* dp = (byte*) &d;
byte[] result = new byte[sizeof(decimal)];
for (int i = 0; i < sizeof(decimal); i++, dp++)
{
result[i] = *dp;
}
return result;
}
And here is reverting back:
private static unsafe decimal GetDecimal(Byte[] bytes)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (bytes.Length != sizeof(decimal))
throw new ArgumentOutOfRangeException("bytes", "length must be 16");
decimal d = 0;
byte* dp = (byte*)&d;
byte[] result = new byte[sizeof(decimal)];
for (int i = 0; i < sizeof(decimal); i++, dp++)
{
*dp = bytes[i];
}
return d;
}
Here is an elegant solution:
// Convert Integer to binary and return as string
private static string GetBinaryString(Int32 n)
{
char[] b = new char[sizeof(Int32) * 8];
for (int i = 0; i < b.Length; i++)
b[b.Length-1 - i] = ((n & (1 << i)) != 0) ? '1' : '0';
return new string(b).TrimStart('0');
}

Categories