I have problem with my binary to ASCII conversion what i have done is i have array of text boxes and i am trying to put binary values into that text boxes and passes those values to the function written as below :
System::String^ conversion(const char* input)
{
int length = strlen(input); //get length of string
int binary[8]; //array used to store 1 byte of binary number (1 character)
int asciiNum = 0; //the ascii number after conversion from binary
System::String^ ascii; //the ascii character itself
int z = 0; //counter used
for(int x = 0; x < length / 8; x++) //reading in bytes. total characters
{
for(int a = 0; a < 8; a++) //store info into binary[0] through binary[7]
{
binary[a] = (int) input[z] - 48; //z never resets
z++;
}
int power[8]; //will set powers of 2 in an array
int counter = 7; //power starts at 2^0, ends at 2^7
for(int x = 0; x < 8; x++)
{
power[x] = counter; //power[] = {7, 6, 5, ..... 1, 0}
counter--; //decrement counter each time
}
for(int y = 0; y < 8; y++) //will compute asciiNum
{
double a = binary[y]; //store the element from binary[] as "a"
double b = power[y]; //store the lement from power[] as "b"
asciiNum += a* pow(2, b);
}
ascii = System::Convert::ToString(asciiNum);
asciiNum = 0; //reset asciiNum for next loop
return ascii;
}
}
the problem is i only get the ASCII value and couldn't get the related character. I want that character any one help me. Thanx in advance.
char asciichar=(unsigned char) asciinum;
This will convert your number to ascii character and you can return the result as char instead of std::string
It is possible to print an integer as a character. Instead of using ToString, you could recast the integers to characters:
(char)asciiNum
Example:
#include <iostream.h>
using namespace std;
int main ()
{
int beta=100;
cout<<"Value of integer is: "<<beta<<endl;
cout <<"Value of char is: "<<(char) beta<<endl;
}
Results:
Value of integer is : 100
Value of char is : d
Related
I have written a program below that converts a string to an int and then converts the decimal number to hexadecimal. I'm struggling to check if the hexadecimal consists only of these characters A, B, C, D, E, F, 1, 0. If so set a flag to true or false.
#include<iostream>
#include <stdlib.h>
#include <string>
#include <sstream>
string solution(string &S){
int n = stoi(S);
int answer;
cout << "stoi(\"" << S << "\") is "
<< n << '\n';
//decToHexa(myint);
// char array to store hexadecimal number
string hexaDeciNum[100];
// counter for hexadecimal number array
int i = 0;
while(n!=0)
{
// temporary variable to store remainder
int temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if(temp < 10)
{
hexaDeciNum[i] = temp + 48;
i++;
}
else
{
hexaDeciNum[i] = temp + 55;
i++;
}
n = n/16;
}
// printing hexadecimal number array in reverse order
for(int j=i-1; j>=0; j--){
cout << hexaDeciNum[j] << "\n";
return "";
}
int main() {
string word = "300";
cout << solution(word);
return 0;
}
OK, it is not the exact answer to what you are asking for, but it is a valuable alternative approach for the entire problem of conversion:
char letter(unsigned int digit)
{
return "0123456789abcdefg"[digit];
// alternatively upper case letters, if you prefer...
}
Now you don't have to differenciate... You can even use this approach for inverse conversion:
int digit(char letter)
{
int d = -1; // invalid letter...
char const* letters = "0123456789abcdefABCDEF";
char* l = strchr(letters, letter);
if(l)
{
d = l - letters;
if(d >= 16)
d -= 6;
}
// alternatively upper case letters, if you prefer...
}
Another advantage: This works even on these strange character sets where digits and letters are not necessarily grouped into ranges (e. g. EBCDIC).
I have to convert a decimal value into a string that shows the binary value, e.g. given 8, I need to print a string "1000". I have the conversion from decimal to binary, but when I print the values directly form the char array, I get little question marks instead of numbers. I know it has something to do with the way char arrays read values, but I can't figure out how to correct the issue.
void dec2Bin(int value, char binaryString[]) {
int remainder = 0;
int binDigit = 0;
int i = 0;
while (value != 0) {
binDigit = value % 2;
value /= 2;
binaryString[i] = char(binDigit);
i++;
}
for (int k = i - 1; k > 0; k--) {
cout << binaryString[k];
}
}
int main()
{
cout << "Enter a decimal number: ";
int num;
cin >> num;
char binaryString[20] = "";
dec2Bin(num, binaryString);
return 0;
}
When you do
binaryString[i] = char(binDigit);
you are assigning the decimal value 0 or 1 to binaryString[i]. That's okay, a char is basically nothing more than a small integer.
The problems comes when you want to print the value, as the only overloaded << operator to handle char treats the characters as a character, and in most encodings the values 0 and 1 are not printable.
There are two solutions:
Either you convert the character you want to print into a larger integer which won't be treated as a character:
cout << static_cast<int>(binaryString[k]);
Or you make the array contain actual printable characters instead:
binaryString[i] = binDigit + '0';
I am going to have an array that is 50 elements long. Each element will contain one digit to form a 50 digit number. What I want to do is multiply this 50 digit long array by another 50 digit long array. The way I thought of doing this was converting each number to form one string. Then produce an algorithm that would multiply line by line 20 digits at a time. Then once the last for loop breaks out of scope, I could reconstruct the new array, digit by digit from converting it from a string. Any alternate ideas before I attempt this, or is what I got what you would do too?
int n1[50], n2[50], out[51];
// n1 and n2 must be populated here
int carry = 0;
for (int cur = 49; cur >= 0; --cur) {
out[cur+1] = n1[cur] * n2[cur] + carry;
carry = out[cur+1] / 10;
out[cur+1] %= 10;
}
out[0] = carry;
I believe you could find the question at leetcode OJ named "Multiply Strings".
This is my solution. Just for reference. Wish this will help :)
class Solution {
public:
string multiply(string num1, string num2) {
int s1(num1.size()), s2(num2.size()), size(s1+s2);
vector<int> digit(size,0), carry(size,0); // digit: store current digit, carry: store carry digit
for(int i = 0; i < s1; ++i){
for(int j = 0; j < s2; ++j){
int mul = num1[s1-1-i]-'0';
int muled = num2[s2-1-j]-'0';
int tmp = mul*muled;
digit[size-1-i-j] += tmp%10; // accum
carry[size-1-i-j-1] += tmp/10; // accum
}
}
int carrFlag(0); // initial carry_flag
for(int i = size-1; i >= 0; --i){ // merge digit and carry
int sum = digit[i] + carry[i] + carrFlag;
ret.insert(ret.begin(),1,'0'+sum%10); // compose result string
carrFlag = sum/10; // update carry_flag
}
int pos(0);
while(ret[pos] == '0') ++pos; // get rid of extra 0's
if(pos>=size) return "0"; // edge case
return ret.substr(pos);
}
private:
string ret;
};
i'm working on a code right now in C++, in which i'm supposed to make a function which receives a string of numbers and converts it into an integer then returns that value. for example if i pass "4569" as string, it will return 4569 integer value.
can anyone help me point out where i'm wrong ??? thanks in advance :)
#include<iostream>
#include<cstdlib>
using namespace std;
void getInput(char arr[] , int size )
{
cout<<"ENTER THE ARRAY"<<endl;
cin.getline(arr,size);
}
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for( int i=y ; i>=0 ; i--)
{
int n= source[i];
sum = (sum + (n * multiply));
multiply = (multiply *10);
}
return sum;
}
int main()
{
const int size =100;
char inputArr [size];
getInput (inputArr, size );
int x = stringToInteger (inputArr );
cout<<"THE RETURNED INTEGER VALUE IS"<<endl;
cout<<x<<endl;
return 0;
}
First, you're starting at the character after the end of the string. If the length (returned by strlen) is y, then valid indexes are 0 <= i < y. So your loop wants to start from y-1.
for( int i=y-1 ; i>=0 ; i--)
^^
Then, you need to convert each ASCII digit into a value from 0 to 9, by subtracting the ASCII value for '0':
int n= source[i] - '0';
^^^^^
Then you should probably detect and handle erroneous input, including values that are too large to be represented by int.
Then, once you've learnt how to implement this in C, throw it away and use the C++ library:
std::string input;
std::getline(std::cin, input);
int x = std::stoi(input);
Try,
#include <stdlib.h>
and in your main():
int x = atoi(inputArr);
I'm not sure why you aren't using atoi or std::stoi, but your algorithm has a logical flaw:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
That said, if this was something other than a homework assignment, you should be using the solutions posted https://stackoverflow.com/a/18238566/529761 or https://stackoverflow.com/a/18238682/529761 (depending on your language requirements).
Also, even this change has 1 potential problem: If the source contains non-numeric characters, it will not work properly. A simple way to approach it is to break out if you encounter a character that shouldn't be there:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
if (n < 0 || n > 9)
break;
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
No need to call a strlen -- until you are allowed to use library functions (the above-mentioned atoi and strtol), you can use this:
int stringToInteger(char *source)
{
int sum = 0;
if (source)
while (*source >= '0' && *source <= '9')
{
sum = 10*sum + *source - '0';
source++;
}
return sum;
}
As implied in about every other answer, you forgot there is a difference between the ASCII character '0' and the binary value 0.
Here is my implementation of Problem 25 - Project Euler (see comments in code for explanation of how it works):
#include <iostream> //Declare headers and use correct namespace
#include <math.h>
using namespace std;
//Variables for the equation F_n(newTerm) = F_n-1(prevTerm) + Fn_2(currentTerm)
unsigned long long newTerm = 0;
unsigned long long prevTerm = 1; //F_1 initially = 1
unsigned long long currentTerm = 1; //F_2 initially = 2
unsigned long long termNo = 2; //Current number for the term
void getNextTerms() { //Iterates through the Fib sequence, by changing the global variables.
newTerm = prevTerm + currentTerm; //First run: newTerm = 2
unsigned long long temp = currentTerm; //temp = 1
currentTerm = newTerm; //currentTerm = 2
prevTerm = temp; //prevTerm = 1
termNo++; //termNo = 3
}
unsigned long long getLength(unsigned long long number) //Returns the length of the number
{
unsigned long long length = 0;
while (number >= 1) {
number = number / 10;
length++;
}
return length;
}
int main (int argc, const char * argv[])
{
while (true) {
getNextTerms(); //Gets next term in the Fib sequence
if (getLength(currentTerm) < 1000) { //Checks if the next terms size is less than the desired length
}
else { //Otherwise if it is perfect print out the term.
cout << termNo;
break;
}
}
}
This works for the example, and will run quickly as long as this line:
if (getLength(currentTerm) < 1000) { //Checks if the next term's size is less than the desired length
says 20 or lower instead of 1000. But if that number is greater than 20 it takes a forever, my patience gets the better of me and I stop the program, how can I make this algorithm more efficient?
If you have any questions just ask in the comments.
There is a closed formula for the Fibonachi numbers (as well as for any linear recurrent sequence).
So F_n = C1 * a^n + C2 * b^n, where C1, C2, a and b are numbers that can be found from the initial conditions, i.e. for the Fib case from
F_n+2 = F_n+1 + F_n
F_1 = 1
F_2 = 1
I don't give their values on purpose here. It's just a hint.
nth fibonacci number is =
(g1^n-g2^n)/sqrt(5).
where g1 = (1+sqrt(5))/2 = 1.61803399
g2 = (1-sqrt(5))/2 = -0.61803399
For finding the length of nth fibonacci number, we can just calculate the log(nth fibonacci number).So, length of nth fibonacci number is,
log((g1^n-g2^n)/sqrt(5)) = log(g1^n-g2^n)-0.5*log(5).
you can just ignore g2^n, since it is very small negative number.
Hence, length of nth fibonacci is
n*log(g1)-0.5*log(5)
and we need to find the smallest value of 'n' such that this length = 1000, so we can find the value of n for which the length is just greater than 999.
So,
n*log(g1)-0.5*log(5) > 999
n*log(g1) > 999+0.5*log(5)
n > (999+0.5*log(5))/log(g1)
n > (999.3494850021680094)/(0.20898764058551)
n > 4781.859263075
Hence, the smallest required n is 4782. No use of any coding, easiest way.
Note: everywhere log is used in base 10.
This will probably speed it up a fair bit:
int getLength(unsigned long long number) //Returns the length of the number when expressed in base-10
{
return (int)log10(number) + 1;
}
...but, you can't reach 1000 digits using an unsigned long long. I suggest looking into arbitrary-precision arithmetic libraries, or languages which have arbitrary-precision arithmetic built in.
You could try computing a Fibonacci number using matrix exponentiation. Then repeated doubling to get to a number that has more than 1000 digits and use binary search in that range to find the first one.
using doubles, you can come to a solution knowing the highest exponential is 308:
get the sequence to the exp of 250, then divide your two numbers by 1e250. Restart the algorithm with those two numbers
if you do this 4 times, you'll get the right answer
C++ code maybe as follows:
#include "iostream"
#include "string.h"
#include "algorithm"
using namespace std;
string addTwoString(string a, string b)
{
if (a.length() == 0)
{
return b;
}
if (b.length() == 0)
{
return a;
}
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string result = "";
string str_1, str_2;
if (a.length() > b.length())
{
str_1 = b;
str_2 = a;
}
else
{
str_1 = a;
str_2 = b;
}
int index = 0;
int value = 0, over_value = 0;
for (; index < str_1.length(); ++index)
{
int temp_1 = (int)(str_1[index] - '0');
int temp_2 = (int)(str_2[index] - '0');
int temp = temp_1 + temp_2 + over_value;
value = temp % 10;
over_value = temp / 10;
char c = (char)(value + '0');
result += c;
}
for (; index < str_2.length(); ++index)
{
int temp_2 = (int)(str_2[index] - '0');
int temp = temp_2 + over_value;
value = temp % 10;
over_value = temp / 10;
char c = (char)(value + '0');
result += c;
}
if (over_value > 0)
{
char c = (char)(over_value + '0');
result += c;
}
reverse(result.begin(), result.end());
return result;
}
int main()
{
string a = "1";
string b = "1";
string c = addTwoString(a, b);
int index = 3;
while (c.length() < 1000)
{
a = b;
b = c;
c = addTwoString(a, b);
++ index;
}
cout << index << endl;
}
I just used a recursive function that adds arrays vertically to complete the problem. Basically zero run time, less than 50 lines of code. Enjoy:
#include <stdio.h>
int Calc_Fib (int numA[], int numB[], int temp[], int index) {
int i = 0;
//Check 1000th digit for non-zero value.
if (numB[999] != 0) return index;
//Add arrays A and B vertically.
for (i = 0; i < 1000; ++i) {
temp[i] += (numA[i] + numB[i]);
if (temp[i] > 9) {
temp[i + 1] = temp[i] / 10;
temp[i] %= 10;
}
numA[i] = numB[i];
numB[i] = temp[i];
temp[i] = 0;
}
Calc_Fib(numA, numB, temp, ++index);
}
int main() {
int numA[1000]; //Holds previous term.
int numB[1000]; //Holds current term.
int temp[1000]; //Holds temporary number for vertical addition.
int i = 0;
int indexVal = 2;
for (i = 0; i < 1000; ++i) {
numA[i] = 0;
numB[i] = 0;
temp[i] = 0;
}
//Initialize first two terms.
numA[0] = (numB[0] = 1);
indexVal = Calc_Fib(numA, numB, temp, indexVal);
printf("Tada: %d\n", indexVal);
return 0;
}