Need help encoding C++ strings by increasing ASCII value - c++

I've looked around everywhere for a C++ code that takes a message from the user, and encodes it by increasing the ASCII value of each character (obviously not very secure, but simple enough). I've managed to put together a program that returns a character of a few values higher, but can not figure out how to do it with a full message including spaces. I plan to make a decoder that does the opposite afterwards. Any help would be really appreciated. Thanks in advance.
Single Value C++ Program -
#include <iostream>
using namespace std;
int main(){
char ascii;
cout << "Enter a character: ";
cin >> ascii;
cout << "Its ascii value is: " << (int) ascii << endl;
return 0;
}
Working Encoder Example in VBS -
set x = WScript.CreateObject("WScript.Shell")
entxtde = inputbox("Enter text to be encoded")
entxtde = StrReverse(entxtde)
x.Run "%windir%\notepad"
wscript.sleep 1000
x.sendkeys encode(entxtde)
function encode(s)
For i = 1 To Len(s)
newtxt = Mid(s, i, 1)
newtxt = Chr(Asc(newtxt)+3)
coded = coded & newtxt
Next
encode = coded
End Function

std::string originalString = "";
std::string newString = "";
int incrementValue = 1;
std::cout << "Input a string to encode: ";
std::cin >> originalString;
for(int i = 0; i < originalString.length(); i++) {
newString += (originalString.at(i) + incrementValue);
}
std::cout >> "New string is " + newString
Just change incrementValue to change how it's encoded.
"Hello" = "Ifmmp" if incrementValue = 1
To reverse it, just change it to subtract incrementValue instead of add in the same kind of for loop. Simple enough I think

This may be done in a single line, or two if you want to stay under 80 columns. Where value is the string you wish to encrypt, and offset the offset value:
auto caesar = [offset](CharT c){return c + offset;};
std::transform(value.begin(), value.end(), value.begin(), caesar);
For bonus points you can make it work with any kind of string by templating on character type:
template <typename CharT>
std::basic_string<CharT> caesarEncode(std::basic_string<CharT> value, CharT offset){
auto caesar = [offset](CharT c){return c + offset;};
std::transform(value.begin(), value.end(), value.begin(), caesar);
return value;
}
Since it looks like you may be experiencing difficulties actually obtaining a string with whitespace, you may get one using the getline function of the standard library, which by default obtains one full line of the source stream.
// narrow (CharT = char)
std::string value;
std::getline(std::cin, value);
// wide (CharT = wchar_t)
std::wstring wvalue;
std::getline(std::wcin, wvalue);
for which actually encoding the string would be done as follows:
char offset = 12;
auto encoded = caesarEncode(value, offset);
wchar_t woffset = 12;
auto wencoded = caesarEncode(wvalue, woffset);
You can see an example in practice here on coliru.

It's simple really. First you take your input as a string. Then, iterate through each character adding by what you want. To ensure the value remains valid and easy to reverse, you mod that value by the max value of a char, i.e. 255.
int main () {
std::string input; // to store the text
std::getline(std::cin, input); // get the text
const int _add = 12; // value added
const int max_size = 255; // max value of a char
for (int i = 0; i < input.size(); ++i)
input[i] = (input[i] + _add) % max_size;
/* now the input is properly modified */
}
note: _add is an int to prevent overflow errors.

Related

Remove trailing zero in C++

I want to ask how to remove trailing zeros after decimal point?
I've read lots of topics about it but I don't understand them clearly. Could you show me any easy understanding ways ?
For example 12.50 to 12.5, but the actual output is 12.50
This is one thing that IMHO is overly complicated in C++. Anyway, you need to specify the desired format by setting properties on the output stream. For convenience a number of manipulators are defined.
In this case, you need to set fixed representation and set precision to 2 to obtain the rounding to 2 decimals after the point using the corresponding manipulators, see below (notice that setprecisioncauses rounding to the desired precision). The tricky part is then to remove trailing zeroes. As far as I know C++ does not support this out of the box, so you have to do some string manipulation.
To be able to do this, we will first "print" the value to a string and then manipulate that string before printing it:
#include <iostream>
#include <iomanip>
int main()
{
double value = 12.498;
// Print value to a string
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value;
std::string str = ss.str();
// Ensure that there is a decimal point somewhere (there should be)
if(str.find('.') != std::string::npos)
{
// Remove trailing zeroes
str = str.substr(0, str.find_last_not_of('0')+1);
// If the decimal point is now the last character, remove that as well
if(str.find('.') == str.size()-1)
{
str = str.substr(0, str.size()-1);
}
}
std::cout << str << std::endl;
}
For C++ check this How to output float to cout without scientific notation or trailing zeros?
using printf() you may use following method to do this,
int main()
{
double value = 12.500;
printf("%.6g", value ); // 12.5 with 6 digit precision
printf("%.6g", 32.1234); // 32.1234
printf("%.6g", 32.12300000); // 32.123
}
std::string example = std::to_string(10.500f);
while (example[example.size() - 1] == '0' || example[example.size() - 1] == '.')
example.resize(example.size() - 1);
Just use 'printf' function.
printf("%.8g",8.230400); will print '8.2304'
float value =4.5300;
printf ("%.8g",value);
will return 4.53.
Try this code . It is quite simple.
I was stumped by this for a while and didn't want to convert to a string to get the job done, so I came up with this:
float value = 1.00;
char buffer[10];
sprintf(buffer, "%.2f", value);
int lastZero = strlen(buffer);
for (int i = strlen(buffer) - 1; i >= 0; i--)
{
if (buffer[i] == '\0' || buffer[i]=='0' || buffer[i]=='.')
lastZero = i;
else
break;
}
if (lastZero==0)
lastZero++;
char newValue[lastZero + 1];
strncpy(newValue, buffer, lastZero);
newValue[lastZero] = '\0';
newValue = 1
you can round-off the value to 2 digits after decimal,
x = floor((x * 100) + 0.5)/100;
and then print using printf to truncate any trailing zeros..
printf("%g", x);
example:
double x = 25.528;
x = floor((x * 100) + 0.5)/100;
printf("%g", x);
output: 25.53

String rotator in C++ (bitwise rotation)

I have string array which has 8 field. 8 bits per field give me 64 bits of memory in single string this type. I want to create rotate function for this string array. For simple for string 20 (in HEX) function RotateLeft(string, 1) gives me 40, like in rotate. Max rotate value is 64, then function must return sent string (RotateLeft(string, 64) == string). I need rotate left and right. I try to create something like this:
std::string RotateLeft(std::string Message, unsigned int Value){
std::string Output;
unsigned int MessageLength = Message.length(), Bit;
int FirstPointer, SecondPointer;
unsigned char Char;
for (int a = 0; a < MessageLength; a++){
FirstPointer = a - ceil(Value / 8.);
if (FirstPointer < 0){
FirstPointer += MessageLength;
}
SecondPointer = (FirstPointer + 1) % MessageLength;
Bit = Value % 8;
Char = (Message[FirstPointer] << Bit) | (Message[SecondPointer] & (unsigned int)(pow(2, Bit) - 1));
Output += Char;
}
return Output;
}
It working for value 64, but not for other values. For simple for HEX string (function get string elements as decimal values but it is for better reading) when I sent this value: 243F6A8885A308D3 and execute RotateLeft(string, 1) I received A6497ED4110B4611. When I check this in Windows Calc it now valid value. Anyone can help me and show where I do mistake?
I am not sure if I correctly understand what you want to do, but somehow to me it looks like you are doing something rather simple in a complicated way. When shifting numbers, I would not put them in a string. However, once you have it as a string, you could do this:
std::string rotate(std::string in,int rot){
long long int number;
std::stringstream instream(in);
instream >> number;
for (int i=0;i<rot;i++){number *= 2;}
std::stringstream outstream;
outstream << number;
return outstream.str();
}
...with a small modification to allow also negative shifts.
You have a hex value in a string, you want to rotate it as if it was actually a number. You could just change it to an actual number, then back into a string:
// Some example variables.
uint64_t x, shift = 2;
string in = "fffefffe", out;
// Get the string as a number
std::stringstream ss;
ss << std::hex << in;
ss >> x;
// Shift the number
x = x << shift;
// Convert the number back into a hex string
std::ostringstream ss2;
ss2 << std::hex << x;
// Get your output.
out = ss2.str();
Here is a live example.

Base encoding impossible with leading 0?

I am trying to encode a string to base36.
static char *decode(unsigned long long value)
{
char base36[37] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char buffer[14];
unsigned int offset = sizeof(buffer);
buffer[--offset] = '\0';
do {
buffer[--offset] = base36[value % 36];
} while (value /= 36);
return _strdup(&buffer[offset]);
}
int main()
{
char original[8] = "0XDX3A1";
unsigned long long encoded = _strtoui64(original, NULL, 36);
char *decoded = decode(encoded);
cout << "Original: " << original << " Decoded: " << decoded << endl;
return 0;
}
The problem here is, while those functions work OK: if the string I am trying to encode has a leading 0 the decoded string is one character (or more) less than the original.
How to deal with this?
If you decode the string "01234" as a base-16 string (for example), you get the integer value 4660 (0x1234) -- exactly the same integer value you get by decoding the string "1234" or "00001234" as a base-16 string. By converting the string to an integer, you've thrown away any information about leading zeros. You've also discarded any information about uppercase vs. lowercase letters, assuming that A and a represent the same value.
Converting that integer value back to a string isn't going to restore that leading 0 unless you add it explicitly. And if you want to add that leading 0 (or multiple 0s) if and only if they were present in the original string, you're going to have to store that information somehow.
Introduce a new variable in your main, called zeroCount in main
Introduce a 2nd argument to function decode, called zeroCount
Count the amount of leading zeroes in the original to the zeroCount in main
Place zeroes to buffer[--offset] until you consume all the zeroCount before the return
Like this:
static char *decode( unsigned long long value, int zeroCount )
{ // introduced zeroCount argument there ^
char base36[37] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char buffer[14];
unsigned int offset = sizeof( buffer );
buffer[--offset] = '\0';
do {
buffer[--offset] = base36[value % 36];
} while ( value /= 36 );
while ( zeroCount-- ) buffer[--offset] = '0'; // <-- added this
return strdup( &buffer[offset] );
}
int main( )
{
char original[8] = "0XDX3A1";
unsigned long long encoded = _strtoui64( original, NULL, 36 );
int zeroCount = 0; // added
for ( int i = 0; i < sizeof original && original[i] == '0'; i++ ) // these
zeroCount++; // three
char *decoded = decode( encoded, zeroCount ); // <-- called along with zeroCount
cout << "Original: " << original << " Decoded: " << decoded << endl;
return 0;
}
Since there isn't any apparent rule for the 0 appending behaviour you desire, I had to assume that you'd like to have exact many leading zeroes that the original had.
You're calling a function tat takes a string containing a representation of a numeric value and converts it to an unsigned long long . The two string representations '00007' and '7' are both converted to numeric 7, and the leading zeroes are lost.
IF you want, eg, 00000036 to covert to 00000010 in base 36, you'll just have to count the zeroes you want and then decide how many of them to replace ( would it depend on the relative lengths of base 10 and base 36 strings? )
But it seems poor practice in the conversion functions. better, in my mind, to add leading zeroes when outputting the value. As many have commented, they have no significance and should not be part of the conversion logic.
I'd suggest you to create a wrapper around your method, and pass it a length parameter.
Eg.
char * wrap_base36enc(int out_len, unsigned long long value){
char pre_str[MAX_VAL]="", *ans = base36enc(value);
len -= strlen(ans);
while(len--){
strcat(pre_str,"0");
}
strcat(pre_str,ans);
return pre_str;
}

Converting a string of numbers to any form of an int

As a part of a larger program, I must convert a string of numbers to an integer(eventually a float). Unfortunately I am not allowed to use casting, or atoi.
I thought a simple operation along the lines of this:
void power10combiner(string deciValue){
int result;
int MaxIndex=strlen(deciValue);
for(int i=0; MaxIndex>i;i++)
{
result+=(deciValue[i] * 10**(MaxIndex-i));
}
}
would work. How do I convert a char to a int? I suppose I could use ASCII conversions, but I wouldn't be able to add chars to ints anyways(assuming that the conversion method is to have an enormous if statement that returns the different numerical value behind each ASCII number).
There are plenty of ways to do this, and there are some optimization and corrections that can be done to your function.
1) You are not returning any value from your function, so the return type is now int.
2) You can optimize this function by passing a const reference.
Now for the examples.
Using std::stringstream to do the conversion.
int power10combiner(const string& deciValue)
{
int result;
std::stringstream ss;
ss << deciValue.c_str();
ss >> result;
return result;
}
Without using std::stringstream to do the conversion.
int power10combiner(const string& deciValue)
{
int result = 0;
for (int pos = 0; deciValue[pos] != '\0'; pos++)
result = result*10 + (deciValue[pos] - '0');
return result;
}
EDITED by suggestion, and added a bit of explanation.
int base = 1;
int len = strlen(deciValue);
int result = 0;
for (int i = (len-1); i >= 0; i--) { // Loop right to left. Is this off by one? Too tired to check.
result += (int(deciValue[i] - '0') * base); // '0' means "where 0 is" in the character set. We are doing the conversion int() because it will try to multiply it as a character value otherwise; we must cast it to int.
base *= 10; // This raises the base...it's exponential but simple and uses no outside means
}
This assumes the string is only numbers. Please comment if you need more clarification.
You can parse a string iteratively into an integer by simply implementing the place-value system, for any number base. Assuming your string is null-terminated and the number unsigned:
unsigned int parse(const char * s, unsigned int base)
{
unsigned int result = 0;
for ( ; *s; ++s)
{
result *= base;
result += *s - '0'; // see note
}
return result;
}
As written, this only works for number bases up to 10 using the numerals 0, ..., 9, which are guaranteed to be arranged in order in your execution character set. If you need larger number bases or more liberal sets of symbols, you need to replace *s - '0' in the indicated line by a suitable lookup mechanism that determines the digit value of your input character.
I would use std::stringstream, but nobody posted yet a solution using strtol, so here is one. Note, it doesn't perform handle out-of-range errors. On unix/linux you can use errno variable to detect such errors(by comparing it to ERANGE).
BTW, there are strtod/strtof/strtold functions for floating-point numbers.
#include <iostream>
#include <cstdlib>
#include <string>
int power10combiner(const std::string& deciValue){
const char* str = deciValue.c_str();
char* end; // the pointer to the first incorrect character if there is such
// strtol/strtoll accept the desired base as their third argument
long int res = strtol(str, &end, 10);
if (deciValue.empty() || *end != '\0') {
// handle error somehow, for example by throwing an exception
}
return res;
}
int main()
{
std::string s = "100";
std::cout << power10combiner(s) << std::endl;
}

How to convert an int to a binary string representation in C++

I have an int that I want to store as a binary string representation. How can this be done?
Try this:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<32> x(23456);
std::cout << x << "\n";
// If you don't want a variable just create a temporary.
std::cout << std::bitset<32>(23456) << "\n";
}
I have an int that I want to first convert to a binary number.
What exactly does that mean? There is no type "binary number". Well, an int is already represented in binary form internally unless you're using a very strange computer, but that's an implementation detail -- conceptually, it is just an integral number.
Each time you print a number to the screen, it must be converted to a string of characters. It just so happens that most I/O systems chose a decimal representation for this process so that humans have an easier time. But there is nothing inherently decimal about int.
Anyway, to generate a base b representation of an integral number x, simply follow this algorithm:
initialize s with the empty string
m = x % b
x = x / b
Convert m into a digit, d.
Append d on s.
If x is not zero, goto step 2.
Reverse s
Step 4 is easy if b <= 10 and your computer uses a character encoding where the digits 0-9 are contiguous, because then it's simply d = '0' + m. Otherwise, you need a lookup table.
Steps 5 and 7 can be simplified to append d on the left of s if you know ahead of time how much space you will need and start from the right end in the string.
In the case of b == 2 (e.g. binary representation), step 2 can be simplified to m = x & 1, and step 3 can be simplified to x = x >> 1.
Solution with reverse:
#include <string>
#include <algorithm>
std::string binary(unsigned x)
{
std::string s;
do
{
s.push_back('0' + (x & 1));
} while (x >>= 1);
std::reverse(s.begin(), s.end());
return s;
}
Solution without reverse:
#include <string>
std::string binary(unsigned x)
{
// Warning: this breaks for numbers with more than 64 bits
char buffer[64];
char* p = buffer + 64;
do
{
*--p = '0' + (x & 1);
} while (x >>= 1);
return std::string(p, buffer + 64);
}
AND the number with 100000..., then 010000..., 0010000..., etc. Each time, if the result is 0, put a '0' in a char array, otherwise put a '1'.
int numberOfBits = sizeof(int) * 8;
char binary[numberOfBits + 1];
int decimal = 29;
for(int i = 0; i < numberOfBits; ++i) {
if ((decimal & (0x80000000 >> i)) == 0) {
binary[i] = '0';
} else {
binary[i] = '1';
}
}
binary[numberOfBits] = '\0';
string binaryString(binary);
http://www.phanderson.com/printer/bin_disp.html is a good example.
The basic principle of a simple approach:
Loop until the # is 0
& (bitwise and) the # with 1. Print the result (1 or 0) to the end of string buffer.
Shift the # by 1 bit using >>=.
Repeat loop
Print reversed string buffer
To avoid reversing the string or needing to limit yourself to #s fitting the buffer string length, you can:
Compute ceiling(log2(N)) - say L
Compute mask = 2^L
Loop until mask == 0:
& (bitwise and) the mask with the #. Print the result (1 or 0).
number &= (mask-1)
mask >>= 1 (divide by 2)
I assume this is related to your other question on extensible hashing.
First define some mnemonics for your bits:
const int FIRST_BIT = 0x1;
const int SECOND_BIT = 0x2;
const int THIRD_BIT = 0x4;
Then you have your number you want to convert to a bit string:
int x = someValue;
You can check if a bit is set by using the logical & operator.
if(x & FIRST_BIT)
{
// The first bit is set.
}
And you can keep an std::string and you add 1 to that string if a bit is set, and you add 0 if the bit is not set. Depending on what order you want the string in you can start with the last bit and move to the first or just first to last.
You can refactor this into a loop and using it for arbitrarily sized numbers by calculating the mnemonic bits above using current_bit_value<<=1 after each iteration.
There isn't a direct function, you can just walk along the bits of the int (hint see >> ) and insert a '1' or '0' in the string.
Sounds like a standard interview / homework type question
Use sprintf function to store the formatted output in the string variable, instead of printf for directly printing. Note, however, that these functions only work with C strings, and not C++ strings.
There's a small header only library you can use for this here.
Example:
std::cout << ConvertInteger<Uint32>::ToBinaryString(21);
// Displays "10101"
auto x = ConvertInteger<Int8>::ToBinaryString(21, true);
std::cout << x << "\n"; // displays "00010101"
auto x = ConvertInteger<Uint8>::ToBinaryString(21, true, "0b");
std::cout << x << "\n"; // displays "0b00010101"
Solution without reverse, no additional copy, and with 0-padding:
#include <iostream>
#include <string>
template <short WIDTH>
std::string binary( unsigned x )
{
std::string buffer( WIDTH, '0' );
char *p = &buffer[ WIDTH ];
do {
--p;
if (x & 1) *p = '1';
}
while (x >>= 1);
return buffer;
}
int main()
{
std::cout << "'" << binary<32>(0xf0f0f0f0) << "'" << std::endl;
return 0;
}
This is my best implementation of converting integers(any type) to a std::string. You can remove the template if you are only going to use it for a single integer type. To the best of my knowledge , I think there is a good balance between safety of C++ and cryptic nature of C. Make sure to include the needed headers.
template<typename T>
std::string bstring(T n){
std::string s;
for(int m = sizeof(n) * 8;m--;){
s.push_back('0'+((n >> m) & 1));
}
return s;
}
Use it like so,
std::cout << bstring<size_t>(371) << '\n';
This is the output in my computer(it differs on every computer),
0000000000000000000000000000000000000000000000000000000101110011
Note that the entire binary string is copied and thus the padded zeros which helps to represent the bit size. So the length of the string is the size of size_t in bits.
Lets try a signed integer(negative number),
std::cout << bstring<signed int>(-1) << '\n';
This is the output in my computer(as stated , it differs on every computer),
11111111111111111111111111111111
Note that now the string is smaller , this proves that signed int consumes less space than size_t. As you can see my computer uses the 2's complement method to represent signed integers (negative numbers). You can now see why unsigned short(-1) > signed int(1)
Here is a version made just for signed integers to make this function without templates , i.e use this if you only intend to convert signed integers to string.
std::string bstring(int n){
std::string s;
for(int m = sizeof(n) * 8;m--;){
s.push_back('0'+((n >> m) & 1));
}
return s;
}