How do i target a specific digit in a multiple-digit number - c++

So I'm making a binary->decimal program where i need to target a specific digit in the number which is inputed, so for instance if the input is 100110110, how do i target the fourth digit, in this case obviously being 1, and the fifth, sixth, ... how many ever digits there are?

If the input is a binary string, store the input in a string and process it using a loop
string num = "1001010";
int l = num.length();
for(int i=0; i<l; i++) {
// num[i] is the (i+1)th bit from left;
}

how many ever digits there are?
these are called bits. To find number of bits in a variable use sizeof operator that returns number of bytes.
sizeof(variable) * 8
how do i target the fourth digit
you can test a bit with operator&:
if (8 == (variable & 8))
...
There are already detailed answers on how to do that: How do you set, clear, and toggle a single bit in C/C++?

Related

C++: Doubling digits using recursion

This is for my "Intro to C++" course. I need to
Write a program that uses a recursive function double_all_digit that doubles all digit from an integer. For example, double_all_digits(101) will return 110011
My code below works for only one digit; I have no idea how to proceed:
int double_all_digit(int x)
{
if(x < 10)
return (x*10) + x;
}
You have the base case; now for the recursion.
split the number into the 1's digit (use modulus) and the rest.
recur on the rest; your result is that number with all the digits doubled.
multiply that result by 100; add 11 times the 1's digit.
return this value up one level.
Here's a strategy:
convert a digit to a string. (use std::to_string)
iterate over characters in the string and append 2 characters in a new string for each character in the original. (See std::string::append)
convert the resulting string to an integer.
Since it's homework, you'll have to do the coding bit. :)

Why does my If-Else never evaluate to true?

I'm supposed to count the number of times variable integer "num" divided by each of its digit results in a clean quotient (has a remainder of 0).
Note: Each digit is considered to be unique, so each occurrence of the same evenly divisible digit should be counted (i.e.: for 222, the answer is 3).
int solver(int num) //gets an integer
{
string numString = to_string(num); //convert integer to string so i can manipulate individual digits
int divisible=0; //will store a count of digits in "num" which can be divided evenly
for (int x = 1; x <= (end(numString) - begin(numString))/*string length*/; x++)
{
if (numString[x-1] == 0 || (end(numString) - begin(numString))-x >=1) //ignore digits which are 0 and or 0s that are last in the array
++x;
if (num % numString[x - 1] == 0) //THIS NEVER EVALUATES TO TRUE. HOW COME???
divisible++;
}
return divisible; //number of digits in variable "num" which can be evenly divided
}
This function ALWAYS returns 0 (that's what variable int "divisible was initialized to), because the if-else for incrementing it always evaluates to false and is skipped. I have checked and made sure the If-Else arguments hold valid numbers (they're all integers). Is it because they are all integers that the decimal part of the result never reach If-Else for evaluation? That's the best possibility I can come up with, and even then I don't know how to remedy.
learn about size() function of std::string. You don't need end and begin to get the length of a string.
numString[x-1] returns a char an ASCII code, not the digit as numeric value. The ASCII code of 0 in decimal for example is 48. To get the numeric value of a single digit you could do:
numString[x-1] - '0'

what does that mean, C programm for RLE

I am new to C so I do not understand what is happening in this line:
out[counter++] = recurring_count + '0';
What does +'0' mean?
Additionally, can you please help me by writing comments for most of the code? I don't understand it well, so I hope you can help me. Thank you.
#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
void encode(char mass[], char* out, int size)
{
int counter = 0;
int recurring_count = 0;
for (int i = 0; i < size - 1; i++)
{
if (mass[i] != mass[i + 1])
{
recurring_count++;
out[counter++] = mass[i];
out[counter++] = recurring_count + '0';
recurring_count = 0;
}
else
{
recurring_count++;
}
}
}
int main()
{
char data[] = "yyyyyyttttt";
int size = sizeof(data) / sizeof(data[0]);
char * out = new char[size + 1]();
encode(data, out, size);
std::cout << out;
delete[] out;
std::cin.get();
return 0;
}
It adds the character encoding value of '0' to the value in recurring_count. If we assume ASCII encoded characters, that means adding 48.
This is common practice for making a "readable" digit from a integer value in the range 0..9 - in other words, convert a single digit number to an actual digit representation in a character form. And as long as all digits are "in sequence" (only digits between 0 and 9), it works for any encoding, not just ASCII - so a computer using EBCDIC encoding would still have the same effect.
recurring_count + '0' is a simple way of converting the int recurring_count value into an ascii character.
As you can see over on wikipedia the ascii character code of 0 is 48. Adding the value to that takes you to the corresponding character code for that value.
You see, computers may not really know about letters, digits, symbols; like the letter a, or the digit 1, or the symbol ?. All they know is zeroes and ones. True or not. To exist or not.
Here's one bit: 1
Here's another one: 0
These two are only things that a bit can be, existence or absence.
Yet computers can know about, say, 5. How? Well, 5 is 5 only in base 10; in base 4, it would be a 11, and in base 2, it would be 101. You don't have to know about the base 4, but let's examine the base 2 one, to make sure you know about that:
How would you represent 0 if you had only 0s and 1s? 0, right? You probably would also represent the 1 as 1. Then for 2? Well, you'd write 2 if you could, but you can't... So you write 10 instead.
This is exactly analogous to what you do while advancing from 9 to 10 in base 10. You cannot write 10 inside a single digit, so you rather reset the last digit to zero, and increase the next digit by one. Same thing while advancing from 19 to 20, you attempt to increase 9 by one, but you can't, because there is no single digit representation of 10 in base 10, so you rather reset that digit, and increase the next digit.
This is how you represent numbers with just 0s and 1s.
Now that you have numbers, how would you represent letters and symbols and character-digits, like the 4 and 3 inside the silly string L4M3 for example? You could map them; map them so, for example, that the number 1 would from then on represent the character A, and then 2 would represent B.
Of course, it would be a little problematic; because when you do that the number 1 would represent both the number 1 and the character A. This is exactly the reason why if you write...
printf( "%d %c", 65, 65 );
You will have the output "65 A", provided that the environment you're on is using ASCII encoding, because in ASCII 65 has been mapped to represent A when interpreted as a character. A full list can be found over there.
In short
'A' with single quotes around delivers the message that, "Hey, this A over here is to receive whatever the representative integer value of A is", and in most environments it will just be 65. Same for '0', which evaluates to 48 with ASCII encoding.

Convert hex- bin- or decimal string to long long in C++

I have this code which handles Strings like "19485" or "10011010" or "AF294EC"...
long long toDecimalFromString(string value, Format format){
long long dec = 0;
for (int i = value.size() - 1; i >= 0; i--) {
char ch = value.at(i);
int val = int(ch);
if (ch >= '0' && ch <= '9') {
val = val - 48;
} else {
val = val - 55;
}
dec = dec + val * (long long)(pow((int) format, (value.size() - 1) - i));
}
return dec;
}
this code works for all values which are not in 2's complement.
If I pass a hex-string which is supposed to be a negativ number in decimal I don't get the right result.
If you don't handle the minus sign, it won't handle itself.
Check for it, and memorize the fact you've seen it. Then, at
the end, if you'd seen a '-' as the first character, negate
the results.
Other points:
You don't need (nor want) to use pow: it's just
results = format * results + digit each time through.
You do need to validate your input, making sure that the digit
you obtain is legal in the base (and that you don't have any
other odd characters).
You also need to check for overflow.
You should use isdigit and isalpha (or islower and
isupper) for you character checking.
You should use e.g. val -= '0' (and not 48) for your
conversion from character code to digit value.
You should use [i], and not at(i), to read the individual
characters. Compile with the usual development options, and
you'll get a crash, rather than an exception, in case of error.
But you should probably use iterators, and not an index, to go
through the string. It's far more idiomatic.
You should almost certainly accept both upper and lower case
for the alphas, and probably skip leading white space as well.
Technically, there's also no guarantee that the alphabetic
characters are in order and adjacent. In practice, I think you
can count on it for characters in the range 'A'-'F' (or
'a'-'f', but the surest way of converting character to digit
is to use table lookup.
You need to know whether the specified number is to be interpreted as signed or unsigned (in other words, is "ffffffff" -1 or 4294967295?).
If signed, then to detect a negative number test the most-significant bit. If ms bit is set, then after converting the number as you do (generating an unsigned value) take the 1's complement (bitwise negate it then add 1).
Note: to test the ms bit you can't just test the leading character. If the number is signed, is "ff" supposed to be -1 or 255?. You need to know the size of the expected result (if 32 bits and signed, then "ffffffff" is negative, or -1. But if 64 bits and signed, "ffffffff' is positive, or 4294967295). Thus there is more than one right answer for the example "ffffffff".
Instead of testing ms bit you could just test if unsigned result is greater than the "midway point" of the result range (for example 2^31 -1 for 32-bit numbers).

Check if integer is multiple of 8

Hi i'm new to c++ so i'm not sure if this is a really silly question. Basically i'm using a c++ custom action project to interact with my MSI installer. I get a property that my user will have entered, it is an integer. I need to ensure that this is a multiple of 8 and i'm not sure how to go about this. Obviously if it can be divided by 8 it is a multiple but I am not sure how to capture if there is a remainder. Any help would be appreciated or even point me in the right direction. Thanks
Use the "modulo" operator, which gives the remainder from division:
if (n % 8 == 0) {
// n is a multiple of 8
}
Use the "modulo" or "integer remainder operator" %:
int a = ....;
if (a % 8 == 0 ) {
// a is amultiple of 8
}
use operator %
if ( num % 8 == 0 )
{
// num is multple of 8
}
Checking only the last 3 digits of a number does the job.
Even if you are given a huge number in the form of a string where the % operating is not useful you can check if only the last 3 digits are divisible by 8 then the whole number is divisible by 8.
For unsigned integers the three least significant bits are always zero for a multiple of 8, so a bitwise & on these bits should be false. For signed (twos complement) this is only true if the integer is positive, so beware if your input is being stored as signed or not (do you want to accept negative numbers as input). Also note the three least significant bits are zero for zero itself, so think if you want your check to be true when someone inputs zero. From your question it doesn't seem like your code has to be optimized so just use modulo.
I saw someone was using bit operation
bool f( int x){
return !(x & 7);
}
It was said this approach has some problem, but I am not quite sure.