int rem, count = 0;
long int n=0, b, i;
count << "Enter the Binary value to convert in Decimal = ";
cin >> b;
i = b;
while (b > 0)
{
rem = b % 10;
n = n + rem * pow(2, count);
count++;
b = b / 10;
}
cout << "The decimal value of Binary no. = " << i << " = " << n;
getch();
I made this simple program in C++ and now I want to implement it in C# but I couldn't do so because I don't know how to implement the logic which I used in the loop.
Because in C++ the keyword pow is used to multiply the value of 2 so I don't know how to do it in C#.
No, pow() is not a keyword, it's a function from the standard library's math.h.
You can easily replace it in this case, for both C++ and C#, with bit shifting:
(int) pow(2, count) == 1 << count
The above is true for all positive values of count, up to the limit of the platform's/language's precision.
I believe the problem as a whole is much easier to solve using shifting.
Check this:
int bintodec(int decimal);
int _tmain(int argc, _TCHAR* argv[])
{
int decimal;
printf("Enter an integer (0's and 1's): ");
scanf_s("%d", &decimal);
printf("The decimal equivalent is %d.\n", bintodec(decimal));
getchar();
getchar();
return 0;
}
int bintodec(int decimal)
{
int total = 0;
int power = 1;
while(decimal > 0)
{
total += decimal % 10 * power;
decimal = decimal / 10;
power = power * 2;
}
return total;
}
You have to take care of data types in C#
long int n=0, b, i; // long int is not valid type in C#, Use only int type.
Replace pow() to Math.Pow()
pow(2, count); // pow() is a function in C/C++
((int)Math.Pow(2, count)) // Math.Pow() is equivalent of pow in C#.
// Math.Pow() returns a double value, so cast it to int
Have a look at the Math.Pow Method.
In general, the Math class provides much functionality you are looking for.
A complete code example elsewhere on the internet is enter link description here.
public int BinaryToDecimal(string data)
{
int result = 0;
char[] numbers = data.ToCharArray();
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
for (int counter = numbers.Length; counter > 0; counter--)
{
if ((numbers[counter - 1].ToString() != "0") && (numbers[counter - 1].ToString() != "1"))
error = "Invalid Value - This is not a binary number";
else
{
int num = int.Parse(numbers[counter - 1].ToString());
int exp = numbers.Length - counter;
result += (Convert.ToInt16(Math.Pow(2, exp)) * num);
}
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
http://zamirsblog.blogspot.com/2011/10/convert-binary-to-decimal-in-c.html
Related
I am having problem in performing correct calculation in following as result is overflowing so function is not returning correct answer.
public static UInt64 findNwords(UInt64 nletters, UInt64 length)
{
if (nletters == 1) return 1;
UInt64 half1 = nletters / 2;
UInt64 half2 = nletters - half1;
UInt64 loc0 = half1;
UInt64 loc1 = half2;
UInt64 curr = 1;
for (UInt64 i = 1; i < length; i++)
{
curr = (loc0 + loc1);
loc0 = loc1;
loc1 = curr;
}
return (curr * half2) % 100000007;
}
Calling findNwords(1000, 500) should return 6109294. In my case it's returning 19610514. Please help.
Your program is overflowing the 64-bit space at iteration 79. You can easily test this by encapsulating the for-loop with an checked-block:
checked
{
for (UInt64 i = 1; i < length; i++)
{
curr = (loc0 + loc1);
loc0 = loc1;
loc1 = curr;
}
}
This will throw an exception if the one value overflows during an operation. You can't do anything about this, besides changing your algorithm by either using lower values or using a System.Numerics.BigInteger instead of UInt64. The second solution requires you to add the System.Numerics assembly as reference. By doing this the algorithm returns the expected value of 6109294 for your example.
To convert an integer value, manually, to binary string you (one technique is to) continuously divide by 2 till the quotient > 0 and append the remainder in reverse order.
string decimalToBinary(int n)
{
string binary = string.Empty;
while (n > 0)
{
// get the LSB
int remainder = n % 2;
// truncate the LSB
n /= 2;
// insert remainder in front
binary = remainder.ToString() + binary;
}
return binary;
}
However, I can't figure out how to convert a fraction (floating point number like for example -0.30), to binary string. More specifically what algorithm should I use. Could anyone suggest an idea?
To convert an integer value, manually
Note that since your input is a an integer which can be negative or zero. But your condition for the while loop is while (n > 0)
Therefore, your code right now cannot handle the situation when the input is 0 (it will return string.Empty) or negative (it will return nothing).
To fix it, you may consider to change your input to uint and make special case for n == 0:
string decimalToBinary(uint n) //note this uint
{
if (n == 0) //special case
return "0";
string binary = string.Empty;
while (n > 0)
{
// get the LSB
uint remainder = n % 2;
// truncate the LSB
n /= 2;
// insert remainder in front
binary = remainder.ToString() + binary;
}
return binary;
}
Or you change it internally:
private string decimalToBinary(int n) {
string binary = string.Empty;
if (n == 0)
return "0";
uint p = (uint)n; //note this cast
while (p > 0) {
// get the LSB
uint remainder = p % 2;
// truncate the LSB
p /= 2;
// insert remainder in front
binary = remainder.ToString() + binary;
}
return binary;
}
Then you should get what you want.
Here is a C++ implementation for fraction to binary conversion:
double frac = .1;
int digits = 1, intpart;
cout <<".";
while (digits < 32 && frac != 0.)
{
frac = frac * 2;
intpart = frac;
frac = frac - intpart;
cout << intpart;
digits++;
}
Output: .0001100110011001100110011001100
or using recursion:
#include <iostream>
using namespace std;
void fractobin(double frac, int digits);
//==========================================================
int main()
{
cout <<".";
fractobin(.1, 1);
return 0;
}
//==========================================================
void fractobin(double frac, int digits)
{
int intpart;
if (digits >=32 || frac==0.)
{
return;
}
else
{
frac = frac * 2;
intpart = frac;
cout << intpart;
fractobin(frac - intpart, ++digits);
return;
}
}
Assume that I want to get sum of all squares from M to N. I googled a bit and found this formula:
(1^2 + 2^2 + 3^2 + ... + N^2) = (N * (N + 1) * (2N + 1)) / 6
so I write this code:
static void Main(string[] args)
{
const int from = 10;
const int to = 50000;
Console.WriteLine(SumSquares(from, to));
Console.WriteLine(SumSquares2(from, to));
}
static long SumSquares(int m, int n)
{
checked
{
long x = m - 1;
long y = n;
return (((y*(y + 1)*(2*y + 1)) - (x*(x + 1)*(2*x + 1)))/6);
}
}
static long SumSquares2(int m, int n)
{
long sum = 0;
for (int i = m; i <= n; ++i)
{
sum += i * i;
}
return sum;
}
it works fine until 40k, but when N becomes 50k it fails. Output for 50k:
41667916674715
25948336371355
Press any key to continue . . .
I think it's an overflow or something, so I added checked keyword and tried to change long to double, but I got the same result. How can it be explained? How to get correct result without loops?
Your second method is overflowing because you are using an int in the loop. Change it to a long as follows (and also add checked):
static long SumSquares2(int m, int n)
{
checked
{
long sum = 0;
for (long i = m; i <= n; ++i)
{
sum += i*i;
}
return sum;
}
}
What was going wrong is that i*i was being calculated internally as an int data type even though the result was being cast to a long data type (i.e. the variable sum), and so it overflowed.
While you are using long for the result, you are still using int for the operators. I would define M and N as long or even BigInteger, and the same for the result. If you do not, you are probably doing int arithmetic still, even though your result is of type long.
I tried your code, and got the results you got. But then I changed every int to long and got the two numbers to match, up to an N of 1600000.
Using BigInteger, I am up to 160000000 and still working ok (result for m=10 and n=160000000 is 13653333461333333359999715, both ways).
To use BigInteger, you will need to add a reference to the System.Numerics dll to your project, and you will need to have a statement at the top of your code including that library.
using System.Numerics;
namespace ConsoleFiddle
{
class Program
{
static void Main(string[] args)
{
BigInteger from = 10;
BigInteger to = 160000000;
Console.WriteLine(SumSquares(from, to));
Console.WriteLine(SumSquares2(from, to));
Console.ReadKey();
}
static BigInteger SumSquares(BigInteger m, BigInteger n)
{
checked
{
BigInteger x = m - 1;
BigInteger y = n;
return (((y * (y + 1) * (2 * y + 1)) - (x * (x + 1) * (2 * x + 1))) / 6);
}
}
static BigInteger SumSquares2(BigInteger m, BigInteger n)
{
checked
{
BigInteger sum = 0;
for (BigInteger i = m; i <= n; ++i)
{
sum += i * i;
}
return sum;
}
}
For an M of 4000000000000000000 (4 x 10^18), and an N of 4000000000100000000. This code still works and gives an immediate result with the first method (1600000016040000000400333333338333333350000000). With the second method it takes it a little while (100 million loop iterations) but gives the same result.
Most probably you are experiencing integer overflow, as the range of long is limited. Probably you have disabled exceptions for integer overflow, so no exception is thrown. The exceptions for integer overflow can be disabled and enabled in the project properties in Visual Studio, if I'm not mistaken.
It was an interview question asked to me - write itoa conversion without using any builtin functions.
The following is the algorithm I am using. But ('0' + n % 10); is throwing an error:
cannot convert string to int
private static string itoa(int n)
{
string result = string.Empty;
char c;
bool sign = n > 0 ? true : false;
while (true)
{
result = result + ('0' + n % 10); //'0'
n = n / 10;
if(n <= 0)
{
break;
}
}
if(sign)
{
result = result + '-';
}
return strReverse(result);
}
I'm unclear why you'd want to do this; just call ToString on your integer. You can specify whatever formatting you need with the various overloads.
As #minitech commented, we usually just use ToString() to do that in C#. If you really want to write the algorithm on your own, the following is an implementation:
public static partial class TestClass {
public static String itoa(int n, int radix) {
if(0==n)
return "0";
var index=10;
var buffer=new char[1+index];
var xlat="0123456789abcdefghijklmnopqrstuvwxyz";
for(int r=Math.Abs(n), q; r>0; r=q) {
q=Math.DivRem(r, radix, out r);
buffer[index-=1]=xlat[r];
}
if(n<0) {
buffer[index-=1]='-';
}
return new String(buffer, index, buffer.Length-index);
}
public static void TestMethod() {
Console.WriteLine("{0}", itoa(-0x12345678, 16));
}
}
It works only for int. The range int is -2147483648 to 2147483647, the length in the string representation would be max to 11.
For the signature of itoa in C is char * itoa(int n, char * buffer, int radix);, but we don't need to pass the buffer in C#, we can allocate it locally.
The approach that add '0' to the remainder may not work when the radix is greater than 10; if I recall correctly, itoa in C supports up to 36 based numbers, as this implementation is.
('0' + n % 10) results in an int value, so you should cast it back to char. There are also several other issues with your code, like adding - sign on the wrong side, working with negative values, etc.
My version:
static string itoa(int n)
{
char[] result = new char[11]; // 11 = "-2147483648".Length
int index = result.Length;
bool sign = n < 0;
do
{
int digit = n % 10;
if(sign)
{
digit = -digit;
}
result[--index] = (char)('0' + digit);
n /= 10;
}
while(n != 0);
if(sign)
{
result[--index] = '-';
}
return new string(result, index, result.Length - index);
}
In C#, is it possible to perform a sum of two 32-bit integers without using things like if..else, loops etc?
That is, can it be done using only the bitwise operations OR (|), AND (&), XOR (^), NOT (!), shift left (<<) and shift right (>>)?
Here is an example for your amusement
unsigned int myAdd(unsigned int a, unsigned int b)
{
unsigned int carry = a & b;
unsigned int result = a ^ b;
while(carry != 0)
{
unsigned int shiftedcarry = carry << 1;
carry = result & shiftedcarry;
result ^= shiftedcarry;
}
return result;
}
The loop could be unrolled. Number of times it executes, depends on the number of bits set in operands, but it's never greater than the width of unsigned int. Once carry becomes 0, next iterations don't change anything.
Try this:
private int add(int a, int b) {
if(b == 0)
return a;
return add( a ^ b, (a & b) << 1);
}
Edit:
Corrected if statement
Think about how addition happens bit by bit. Shift the values to get each bit of each operand in turn, then look at the four possible values for the two bits and work out what the result bit should be and whether there's a carry bit to worry about. Then see how the result and carry can be caculated using the bitwise ops.
static int binaryadd(int x, int y)
{
while (x != 0)
{
int c = y & x;
y = y ^ x;
x = c << 1;
}
return y;
}
public static int getSum(int p, int q)
{
int carry=0, result =0;
for(int i=0; i<32; i++)
{
int n1 = (p & (1<<(i)))>>(i); //find the nth bit of p
int n2 = (q & (1<<(i)))>>(i); //find the nth bit of q
int s = n1 ^ n2 ^ carry; //sum of bits
carry = (carry==0) ? (n1&n2): (n1 | n2); //calculate the carry for next step
result = result | (s<<(i)); //calculate resultant bit
}
return result;
}
Taking 32 bit as int takes 32 bit. Thanks!!!
int Add(int a, int b)
{
int result = 0,
// carry now contains common set bits of "a" and "b"
carry = a & b;
if (Convert.ToBoolean(carry))
{
// Sum of bits of "a" and "b" where at least one
// of the bits is not set
result = a ^ b;
// carry is shifted by one so that adding it
// to "a" gives the required sum
carry = carry << 1;
result = add(carry, result);
}
else
{
result = a ^ b;
}
return result;
}
Sum of two bits can be performed using the XOR ^ operator and carry bit can be obtained by using AND & operator.
Provided a and b don't have set bits at the same position, then using ^ operator gives the sum of a and b.
Comments from geeksforgeeks
public int getSum(int a, int b) {
while(b!=0){
int temp=a;
a=a^b;
b=(temp&b)<<1;
}
return a;
}
int b = 25;
for (int t = 128; t > 0; t = t / 2)
{
if ((b & t) != 0) Console.Write("1 ");
if ((b & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
//b = (sbyte)~b;
int e = 22;
for (int t = 128; t > 0; t = t / 2)
{
if ((e & t) != 0) Console.Write("1 ");
if ((e & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
int c = b | e;
for (int t = 128; t > 0; t = t / 2)
{
if ((c & t) != 0) Console.Write("1 ");
if ((c & t) == 0) Console.Write("0 ");
}