Converting from ASCII back to char - c++

I have a function that already converts a string to ASCII ints, but how to I do the reverse? Thanks

You question is not clear. Giving you solution based on assumption that your ASCII ints (in your terms) stored in a vector<int>
Below function will convert it into string:
std::string
AsciiIntToString ( std::vector<int> const& ascii_ints )
{
std:: string ret_val;
std::vector<int>:: const_iterator it = ascii_ints. begin ();
for ( ; it != ascii_ints. end (); ++it ) {
if ( *it < 0 || *it > 255) throw std::exception ("Invalid ASCII code");
ret_val += static_cast<char>(*it);
}
return ret_val;
}

Here are some examples that convert between number and the textual representation of the number in binary format using std::bitset (only works for character sets that can be represented by 7 bits (as US-ASCII for example)):
char c = 'a';
// char to int.
int i = static_cast<int>(c);
// int to string (works for char to string also).
std::string bits = std::bitset<8>(i).to_string();
// string to (unsigned long) int.
unsigned long ul = std::bitset<8>(bits).to_ulong();
// int to char.
c = static_cast<char>(ul);

Here is a much simpler way!
void convertToString()
{
char redo;
int letter;
int length;
do{
cout<< "How long is your word \n";
cin >> length;
cout << "Type in the letter values \n";
for (int x = 0; x < length; x++)
{
cin >> letter;
cout << char (letter);
}
cout << "\n To enter another word hit R" << endl;
cin >> redo;
} while (redo == 'R');
}

The use of the neologism "ASCII 'int'" was an imprecise--but not an unclear--reference to ASCII codes. The reference was clear because all of the ASCII codes are whole numbers, just like integers.
The original poster was able to translate an ASCII character into decimal, presumably using a function.
In MySQL, this would be: SELECT ASCII('A') [FROM DUAL];, which returns 65.
To reverse direction, use the char() function:
SELECT CHAR(65) [FROM DUAL];
Perhaps this would be a good work-around for you.
I would recommend using non-GUI client.

The best way to convert static to cast is
int it=5;
char W = static_cast<char>(*it);

You just have to store it in a char variable:
//Let's say your original char was 'A'...
int asciivalue = int('A');
// Now asciivalue = 65
//to convert it back:
char orig = asciivalue;
cout << orig << endl;
It'll output 'A'.

Related

Looping through string of integers gives me completely different numbers?

I'm a beginner to C++ so forgive me if I'm making a stupid mistake here.
I want to loop through a string of integers in the following code:
#include <string>
using namespace std;
int main() {
string str = "12345";
for (int i : str) {
cout << i << endl;
}
return 0;
}
But I receive the output:
49
50
51
52
53
I know that I get normal output if I use char instead of int, but why do I receive an output of integers 48 more than they should be?
When you loop through a string you get elements of type char. If you convert a char to an int you get the ASCII value of the char, which is what happens when you do:
string str = "12345";
for (int i : str) { // each char is explicitly converted to int
cout << i << endl; // prints the ascii value
}
The ASCII value of '0' is 48, and '1' is 49, etc, which explains the output you get.
Just what #cigien said, You just need to change it from int to char i.e
string str = "12345";
for (char i : str) {
cout << i << endl;
}
Or one solution for all auto keyword
string str = "12345";
for (auto i : str) {
cout << i << endl;
}
The first thing you need to know is that a string is an array/sequence of chars.
You can think of a char as a single character.
But the way it is encoded is as a number.
For example, the char 'a' is encoded (in ASCII) as the number 97.
Now your for loop says int i: str.
You're telling it to look for integers in the string.
But a string is an array/sequence of chars, not of integers.
So the loop takes each char,
and instead of looking at what the character itself is,
it gives you the integer encoding value of the char,
the ASCII value.
Now the numbers are encoded with the char '0' having the lowest encoding value,
'1' having the next value,
'2', having the next,
and so on through digit '9'.
I can never remember what the actual ASCII value for '0' is . . . .
But because the digit chars are encoded consecutively in this way,
you can convert any digit char to its int value by subtracting the underlying integer encoding value of '0'.
#include <string>
using namespace std;
int main() {
string str = "12345";
for (char c: str) {
cout << (c - '0') << endl; // gives you the actual int value, but only works if the char is actually a digit
}
return 0;
}
for (int i : str) { is infact syntactic sugar for
for (auto iterator = str.begin(); iterator != str.end(); iterator++) {
int i = (int) *iterator;
But the *-operator from string::iterator is infact an overload which returns the current char. It will as such be casted to an int. What you then see is this number. It is the integer value of the byte. Not necessarily ASCII. It could be ANSI too.

Output is not as expected

The idea of my program was to print individual digits of n.
But instead it prints all the digits at once in the first line and a bunch of zeroes or garbage values in subsequent lines.
I want to access each individual number as we can do with arrays.
Suppose the input is 1234, why doesn't it print 1\n2\n3\n4?
#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
int main()
{
int* n=(int*)malloc(1000*sizeof(int));
cin>>*n;
int len;
len = log10(*n) + 1;
for(int i=0;i<len;i++)
{
cout<<n[i]<<endl;
}
}
n is declared as a pointer to a memory location which can store 1000 integer entities. When you use cin>>*n;, an integer value is read as input and store at the first memory block among the 1000 blocks. The individual digits of the integer are not stored in separate blocks, hence you can't print them separately.
For example, if the input is 123,
n[0] stores 123, n[1],n[2],...n[999] stores junk values.
To store a value in n[1], you will have to use cin again.
For some reason you think that
int* n=(int*)malloc(1000*sizeof(int));
cin>>*n;
will read a number and put each digit in a different element of the dynamic array n. If that happened then the rest of your code would work (kind of). But of course it doesn't. Instead the number read is put into *n (or, same thing, n[0]) and the rest of the dynamic array elements are uninitialised, which explains the garbage values you see.
I'm struggling to understand why you thought your code might behave in the way you wanted. I guess you are just an optimistic person and think that if you wish hard enough the compiler will understand. This seems to be quite a common attitude among beginners. Unfortunately programming isn't like that.
When you cin >> *n, you don't read the number digit by digit, but read in as a whole.
So when you cin >> *n and type in 1234, *n becomes 1234.
If you want to print all the individual digits, like 1\n2\n3\n4, you need to separate the digits for yourself:
int pos = 1;
while (*n != 0)
{
n[pos] = n % 10;
n /= 10;
++pos;
}
for (--pos; pos > 0; --pos)
{
cout << n[pos] << endl;
}
However, the easiest approach is to read in the number as a string, not a number, then print out the characters, that is the digits, one by one.
char str[1000];
cin >> str;
for (char *s = str; *s; ++s)
{
cout << *s << endl;
}
You can also convert the number into a string, and do the same:
#include <cstring>
using namespace std;
...
char str[1000];
sprintf(str, "%d", *n);
for (char *s = str; *s; ++s)
{
cout << *s << endl;
}
------- Original Answer:
If you want to print the first element of n:
cout << *n;
or
cout << n[0];
Your code
for(int i=0;i<len;i++)
{
cout<<n[i]<<endl;
}
means
cout << n[0] << endl;
cout << n[1] << endl;
cout << n[2] << endl;
...
cout << n[len-1] << endl;

Trying to write a C++ function to un-hex encode a 8 bit char and turn it into an integer

I have a C++ function that converts a unsigned long into a 8 bit hex char string.
I need to come up with a reverse function that takes a 8 bit hex char string and converts it into an unsigned integer representing it's bytes.
Original UINT -> char[8] method:
std::string ResultsToHex( unsigned int EncodeResults)
{
std::cout << "UINT Input ==>";
std::cout << EncodeResults;
std:cout<<"\n";
char _HexCodes[] = "0123456789ABCDEF";
unsigned int HexAccum = EncodeResults;
char tBuf[9];
tBuf[8] = '\0';
int Counter = 8;
unsigned int Mask = 0x0000000F;
char intermed;
// Start with the Least significant digit and work backwards
while( Counter-- > 0 )
{
// Get the hex digit
unsigned int tmp = HexAccum & Mask;
intermed = _HexCodes[tmp];
tBuf[Counter] = intermed;
// Next digit
HexAccum = HexAccum >> 4;
}
std::cout << "Hex char Output ==>";
std::cout << tBuf;
std::cout << "\n";
return std::string(tBuf);
}
And here is the function I am trying to write that would take a char[8] as input and convert into a UINT:
unsigned int ResultsUnhex( char tBuf[9])
{
unsigned int result = 0;
std::cout << "hex char Input ==>";
std::cout << tBuf;
std:cout<<"\n";
//CODE TO CONVERT 8 char (bit) hex char into unsigned int goes here......
//
// while() {}
//
///
std::cout << "UINT Output ==>";
std::cout << result;
std::cout << "\n";
return result;
}
I am new to bit shifts, any help would be greatly appreciated :).
You need to scan the string and convert each hexadecimal character back to it's corresponding 4 bit binary value. You can do this with a simple set of if statements that checks the character to see if it's valid and if so convert it back.
After a character has been converted, shift your result variable left by 4 bits then stuff the converted value into the lower 4 bits of the result.
#include <stdexcept>
unsigned int ConvertHexString(char *str)
{
unsigned int result = 0;
while(*str)
{
char ch = *str++;
// Check for 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9
if(ch >= '0' && ch <= '9')
{
ch -= '0';
}
// Check for a, b, c, d, e, f
else if(ch >= 'a' && ch <= 'f')
{
ch = 10 + (ch - 'a');
}
// Check for A, B, C, D, E, F
else if(ch >= 'A' && ch <= 'F')
{
ch = 10 + (ch - 'A');
}
// Opps! Invalid character
else
{
throw std::invalid_argument("Unknown character in hex string");
}
// Mmmm! Stuffing! Don't forget to check for overflow!
result = (result << 4) | ch;
}
return result;
}
There are several ways to do this but I figured a simple example to get you started would be more helpful.
Obligatory example using the conversion function.
#include <iostream>
int main()
{
std::cout
<< std::hex
<< ConvertHexString("1234567")
<< ConvertHexString("90ABCDEF")
<< std::endl;
}
Outputs...
123456790abcdef
Why do you do it manually? There's plenty of tools that do that for you. For example, stringstream.
This converts an int to a hex-string:
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
[code copied from Integer to hex string in C++ - please see that thread, there's plenty of examples. Upvote there instead of here.]
Add to that "0x" and some field-width manipulators and you may reduce the ResultsToHex to three..five lines.
The stringstream also works the other way. Using >> operator you can just as easily read a hexstring into an integer variable. [Converting Hexadecimal to Decimal, Hex character to int in C++, convert hex buffer to unsigned int, ...]

Brute Force Character Generation in C++

So I'm trying to make a brute force string generator to match and compare strings in CUDA. Before I start trying to mess around with a language I don't know I wanted to get one working in C++. I currently have this code.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int sLength = 0;
int count = 0;
int charReset = 0;
int stop = 0;
int maxValue = 0;
string inString = "";
static const char charSet[] = //define character set to draw from
"0123456789"
"!##$%^&*"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int stringLength = sizeof(charSet) - 1;
char genChars()
{
return charSet[count]; //Get character and send to genChars()
}
int main()
{
cout << "Length of string to match?" << endl;
cin >> sLength;
cout << "What string do you want to match?" << endl;
cin >> inString;
string sMatch(sLength, ' ');
while(true)
{
for (int y = 0; y < sLength; y++)
{
sMatch[y] = genChars(); //get the characters
cout << sMatch[y];
if (count == 74)
{
charReset + 1;
count = 0;
}
if (count == 2147000000)
{
count == 0;
maxValue++;
}
}
count++;
if (sMatch == inString) //check for string match
{
cout << endl;
cout << "It took " << count + (charReset * 74) + (maxValue*2147000000) << " randomly generated characters to match the strings." << endl;
cin >> stop;
}
cout << endl;
}
}
Now this code runs and compiles but it doesn't exactly do what I want it to. It will do 4 of the same character, EX. aaaa or 1111 and then go onto the next without incrementing like aaab or 1112. I've tried messing around with things like this
for (int x = 0; x < sLength; x++)
{
return charSet[count-sLength+x];
}
Which in my mind should work but to no avail.
You basically just need to increment a counter, than convert the count number to base (size of char array)
Here's an example which does normal numbers up to base 16.
http://www.daniweb.com/code/snippet217243.html
You should be able to replace
char NUMS[] = "0123456789ABCDEF";
with your set of characters and figure it out from there. This might not generate a large enough string using a uint, but you should be able to break it up into chunks from there.
Imagine your character array was "BAR", so you would want to convert to a base 3 number using your own symbols instead of 0 1 and 2.
What this does is perform a modulus to determine the character, then divide by the base until the number becomes zero. What you would do instead is repeat 'B' until your string length was reached instead of stopping when you hit zero.
Eg: A four character string generated from the number 13:
14%3 = 2, so it would push charSet[2] to the beginning of the empty string, "R";
Then it would divide by 3, which using integer math would = 4. 4%3 is again 1, so "A".
It would divide by 3 again, (1) 1%3 is 1, so "A".
It would divide by 3 again, (0) -- The example would stop here, but since we're generating a string we continue pushing 0 "B" until we reach 4 our 4 characters.
Final output: BAAR
For an approach which could generate much larger strings, you could use an array of ints the size of your string, (call it positions), initialize all the ints to zero and do something like this on each iteration:
i = 0;
positions[i]++;
while (positions[i] == base)
{
positions[i] = 0;
positions[++i]++;
}
Then you would go through the whole array, and build the string up using charSet[positions[i]] to determine what each character is.

taking big integer input all at a time in C++

i want to take a 1000 digit integer input all at a time,& want to add the digits separately.is there any input method to take such a large input?
You need to input that as a string. Split them, and convert each character to an integer. Add them up, and you're done.
Example, this number here (randomly generated):
9624526619162264306083309360203157186784123851390498919674886891002552146753945797326679482200717699585297042606470048297021049209667042255911984240697992738371633115195140494325737382583412562136836759072897211537655046343769659111215754043609344618490646811291135643554115350431099553593485744944746093896695837300975718819726339233383800764568364950577294931831936979504756278187812548901366714205562309364234394802723329400976924082450161974562063268243689930750925213262044910428021004262080895556879515597779404780565380480750286553508081070834339176079062215815331059349488936312244526697733596052063044560959189161656978673936732284706841120711543620038686227462170335634371808995466024671420024705248851244350701111587608201303840696489479021196275228499780922745352396928865910631672384263395712487735712098161853665189905194589355110620257494673972892816413534347360049692019184831019218764766067298983043791063184786671132332077197148683743991683245617836086353821268720434176862469084808
And here's the C++ program:
int strint(std::string &str) {
int i;
std::stringstream intstr(str);
intstr >> i;
return i;
}
int main () {
std::string strdigit, schar;
int sum = 0;
std::cout << "Enter Digits: ";
std::cin >> strdigit;
std::stringstream ss;
for (int i = 0; i < strdigit.length(); i++) {
ss.clear();
ss << strdigit[i];
ss >> schar;
sum += strint(schar);
}
std::cout << sum;
}
The sum is: 4479
Simply read the digits into a string and use std::accumulate. For example:
std::string str("1234567890"); // your number here
int result = std::accumulate(str.begin(), str.end(), 0, [](int val, char ch)
{
return val + (ch - '0');
});
std::cout << result << '\n'; // display the answer
You need a library to provide support for this.
Read the digits into a string and use a multiprecision math library such as GMP to do the addition. The library should have functions for converting between digit strings and the library's internal representation for numbers.
(Actually, it looks like GMP can read digits directly from an istream, so you may not even need a string.)
I'm a little unclear on the question. If you are adding the digits separately, then I would have thought you were treating it more as a string than an integer (at least, until you start adding up the digits).
Can you clarify how the 1,000-digit integer needs to be stored in memory?
As marlon suggested, why not simply use good 'ol for loop and string?
int main() {
string str = "3985792792679283635";
int len = str.length();
int sum = 0;
for(int i = 0; i < len; i++) {
sum += str[i] - '0';
}
cout << sum << endl;
}