I really wanted to know how do you wrap a value or a letter in C. Say if I were to increment 'z', how can I make it turn to 'a' and vice versa? The same goes with integers. If I have 9, how can I make it turn to 0 upon incrementation?
The operator you are looking for is modulo %.
Wrapping integers is straight forward:
int my_int = /* some value */
int wrapped_my_int = my_int % 10;
To wrap ascii characters is a little more complicated because the start value is not 0. Just need to rebase to 0 first and then back to 'a' based:
char my_char = /* some value */
char wrapped_my_char = (my_char - 'a') % ('z' - 'a' + 1) + 'a';
Related
This question already has answers here:
Why does subtracting '0' in C result in the number that the char is representing?
(8 answers)
Convert char to int in C and C++
(14 answers)
Closed 4 years ago.
m=1e9 + 7;
inline ll rem(char s[],ll m)
{
ll sum=0 , i;
for(i=0;S[i]!='\0';i++)
{
if(sum>=m)
sum %= m;
sum=(sum * 10 + S[i] - '0');
}
return sum%m;
}
here S[i] is a string of integer characters. My question is
what does -'0' does here, also can a character (here S[i]) be automatically converted to integer form is the above
sum=(sum * 10 + S[i] - '0');
equation.
First, you have to remember that characters in C are represented as tiny integers corresponding to the character's value in the machine's character set, which is typically ASCII.
For example, 'A' n ASCII is 65, and '0' is 48.
So if you're converting a string of digits to an integer, you want to do something like
int digit = c - 48;
That converts '0' to 0, '1' to 1, etc.
But that magic number 48 is mystifying, and it's theoretically also wrong on a machine using a character set other than ASCII. So the easier (because you don't have to remember that value 48), self-documenting (as long as your reader understands the idiom), and more portable way is to do
int digit = c - '0';
This works because, as I said, '0' is 48 in ASCII. But, more importantly, even on a non-ASCII machine, '0' is whatever value the character '0' has in that machine's character set, so it's always the right value to subtract, no matter what kind of machine you're using.
In many solutions on codechef for faster input output I came across this expression but I am unable to understand it as I do not have a lot of experience.
inline int scan( ) {
int n=0;
int ch=getchar_unlocked();
while( ch <48 )ch=getchar_unlocked();
while( ch >47 )
n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();
return n;
}
In the above function what is the purpose of the below mentioned expression?
n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();
and what is the meaning of (n<<3)+(n<<1)?
<< is shift left operator, that's easy to find in any C tutorials. Just google for C operator list and see.
(n << 3) + (n << 1) = n*8 + n*2 = n*10
That's an old optimization trick but probably won't be as effective as before in modern architectures with fast multipliers
If your input stream consists of characters 0-9, then the code block
while( ch >47 )
n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();
computes the decimal integral number from the string as long as ch < 58, which is '9'. If ch >= 58, the result is non-sensical.
Let's say the first character when entering the loop is 8. Then,
n = (n<<3)+(n<<1) + ch-'0' = 8
Let's say the second character is 5. Then,
n = (n<<3)+(n<<1) + ch-'0' = 85
and so on.
n<<3 means n is shifted 3 bit to the left and n<<1 means n is shifted 1 bit to the left and then the the ASCII value of 0 is subtracted from ch to get the actual number in int.
Example: when n=2 and n is 1 bit shifted to left it becomes 4.
Because the binary representation of 2 is 010 and when it shifts 1 bit to left it becomes 100 which is the binary representation of 4. It works in the same way for n<<3.
The comma operator separates two expressions. The first is evaluated and then discarded, and the second is then evaluated (and this value can be used). The comma operator has lower precedence than assignment, so the interpretation is as the others have said
n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();
multiply n by 10, add the value of ch's offset from 0, and store the result in n. Then call getchar_unlocked() and assign the return value to ch. The comma isn't doing anything but adding confusion to the code here. It would be better to use two statements.
I've never seen the comma operator used outside of loop initialization/increment, but it is handy there.
for (count = 0, index = 1; index < MAX_INDEX; count += 1, index += 2) {
/* some code */
}
itoa is not an ANSI-C standard therefore doesn't work for GCC
char* itoa(int val, int base){
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base)
buf[i] = "0123456789abcdef"[val % base];
return &buf[i+1];
}
Questions I have
static char buf[32]
Why use static? Can I delete that?
Why i=30?
Shouldn't it be 31? 0 to 31 for 32 bits.
For the for-loop, what is val /= base trying to do?
Inside the for-loop, what does val%base do? I know it's for remainder but how's that relate to here? What's the difference between val/base versus val%base?
1) as #Blastfurnace noted, the static is needed so that the buffer still exists when the function returns
2) i=30 because its the last used index, because the index 31 needs to be NULL (\0). because c works with Null-Terminated-Strings
3) removing the last digit. i.e: val = 12345, base = 10, val / base = 1234, 5 is removed
4) getting the current digit (right to left) , 12345 % 10 = 5 (its also the index of the char array representing the digits (very efficient)
1)static char buf[32]
why use static? can I delete that?
So it doesn't get reloaded everytime the routine is called. No, the routine needs it to store the ascii values to be output.
2)why i=30?
shouldn't be 31? 0 to 31 for 32 bits
Not sure, but 30 characters represents 120 bits, not 30.
3) for the for loop, what does val /=base trying to do?
It's reducing the base on each iteration so the remainder value (used as an index to the array) will be correct.
4)inside the for loop, what does val%base do? I know it's for remainder but how's that relate to here? what's the difference between val/base versus val%base?
It calculates the remainder as an index into buf, to select the correct ascii value. / returns the integer (rounded off) divide, not the remainder of that divide.
Value = (Value/divisor)*divisor + Value%divisor.
thanks
I got a set of characters as input using scanf which is actually like this "1854?156X".
(using scanf("%c",&input[i]) , input is an array of 10 characters);
In further processing of code I want to multiply the (first digit *10) & (second digit *9) and so on.
So, while multiplying it is taking the ASCII value of 1 which is actually (49 *10), instead of (1*10).
input[i]*counter;
where counter is
int counter=10;
How can I convert the char array to integer array where the exact digit should be multiplied instead of ascii value of that character?
If you know ahead of time that you value is ascii then simply subtract the value of '0' from it. E.g. '9' - '0' = 9'
Definitely use atoi(). It spares you a lot of manual character checking.
int input_val = atoi(input);
int temp = input_val;
while(temp)
{
int digit = temp % 10;
temp /= 10;
}
This gives you each digit from right to left in "digit". You can construct your number using addition and multiplying by powers of 10.
Take the ascii value and subtract 48.
That is input[i] - '0'
...or rather use atoi(). It returns zero if it fails on conversion, so you don't need to bother with '?' and such characters in your array while you traverse it.
Use strtol to convert these character strings into integral types.
It's superior to atoi because the failure modes are not ambiguous.
Does it exist a better way to reverse an element of X?
>> X = dec2bin(10)
X = 1010
I did this:
x(i) = num2str(1-str2num(x(i)))
If I understand you correctly, and you want to set one bit to 1 use bitset
bitset( x, bitNumber)
In case you want to flip a bit from 0 to 1 and vice verca, use bitxor
num = bin2dec('101110');
bitNum = 1;
res = bitxor(num, 2^(bitNum-1));
disp(dec2bin(res));
It is better, because you don't need to convert the number to char .
If you want to flip a bit of a numeric value num without converting it first to a character array of '0' and '1', then you can use functions like BITXOR, BITGET, and BITSET (as Andrey also mentions):
num = bitxor(num, 4); %# Flip the bit in the 4's place (i.e. bit 3)
%# Or ...
num = bitset(num, 3, ~bitget(num, 3)); %# Flip bit 3
However, if you do want to operate on the character array, you could also do this very strange thing:
X(i) = 'a' - X(i);
%# Or ...
X(i) = 97 - X(i);
This works because the characters 'a' and X(i) are first converted to their equivalent Unicode UTF-16 numeric values before the mathematical operation is performed. Since the numeric value for 'a' is 97, then a '0' (numeric value 48) or '1' (numeric value 49) subtracted from 'a' will result in the numeric value for the other. The resulting numeric value on the right hand side of the equation is then converted back to a character when it is placed back in the character array X.