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.
Related
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 */
}
I want to take user input entered as an integer, for example (45697), and store the first two digits in an array, vector, or something else such as ( 4 5 6 9 7 ), so that I could then use some function call to check for the first two values (4 5) and perform calculations on them.
The Problem: I don't know how to store the recover those first two values.
Is there a simple function call? Or would I have to store the input first as any array and then extract the first two values, and if so, how?
You can do it easily using conversions to/from strings:
>> x = 45697; % or whatever positive value
>> str = num2str(x);
>> y = [str2num(str(1)) str2num(str(2))]
y =
4 5
This assumes that the number x is positive (if it were negative the first character would not be a digit). That seems to be the case, since according to your comments it represents an electrical resistance.
There is nothing wrong with a string-based approach, but here is a mathematical solution to getting all of the digits:
>> x = 45697
x =
45697
>> numDigits = floor(log10(x)+1)
numDigits =
5
>> tens = 10.^(1:numDigits);
>> digitArray = fliplr(floor(mod(x,tens)./(tens/10)))
digitArray =
4 5 6 9 7
The crux of this method is to use mod to chip off the high digits one at a time, shifting the new first digit down to the ones place, and finally truncating down to the get the integer value at that position.
In the case of the OP, the required values are digitArray(1:2).
Since you are interested in individual digits, you don't even need to invoke str2num. One way is enough as in x_str = num2str(x);, then you subtract '0' with y = x_str(1:2)-'0';.
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.
I have a program I am writing that converts Octal to Decimal numbers. Most of it works.
(more code above this, assume all variables are properly declared).
for(i; i > 0; i--)
{
decimalNumber = (decimalNumber + (number['i'] * pow(8,power)));
power++;
}
The code correctly shifts over to the right to do other digits but it doesn't change the number it is working with. For example, entering 54 in octal results in an output of 36, 4*(8^0) + 4*(8^1) when it should be outputting 4*(8^0) + 5*(8^1), or 44.
'i' is a constant. You probably meant just i. Also, << 3.
As Ignacio pointed out, 'i' is a constant and will cause you to access the same out of bounds array element on each iteration of the loop. Since I assume you start with i equal to the number of digits in the array (you didn't show that code), you want to subtract 1 from it when you use it as an array index.
You're traversing the string in the wrong direction.
Or, better, change your logic:
5 -> 5*8^0
54 -> (5*8^0)*8 + 4
543 -> ((5*8^0)*8 + 4)*8 + 3
number[0] is 5
number[1] is 4
decimalNumber is 0
power is 0
i = 1 downto 0 do
decimalNumber = (decimalNumber + (number[i:1,0] * pow(8,power:0,1)));
power++;
do end
I am looking at the following piece of code:
void printd(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n / 10)
printd(n / 10);
putchar(n % 10 + '0');
}
I understand the first if statement fine, but the second one has me confused on a couple of points.
By itself, since "n" is an integer, I understand that n/10 will shift the decimal point to the left once - effectively removing the last digit of the number; however, I am having a little trouble understanding how this can be a condition by itself without the result being equal to something. Why isn't the condition if ((n/10) >= 0) or something?
Also, why is the '0' passed into the putchar() call?
Can someone tell me how it would read if you were to read it aloud in English?
Thanks!
The n / 10 will evaluate to false if the result is 0, true otherwise. Essentially it's checking if n > 10 && n < -10 (the -10 doesn't come into play here due to the n = -n code)
The + '0' is for character offset, as characters '0'-'9' are not represented by numbers 0-9, but rather at an offset (48-57 with ascii).
Can someone tell me how it would read if you were to read it aloud in English?
If you're talking about the conditional, then I would say "if integer n divided by 10 is not zero"
n/10 will not shift the decimal number since n is an integer. The division will produce the result like this: if n = 25, then n/10 would be 2 (without any decimal points), similarly if n = 9, then n/10 would be 0 in which case if condition would not be satisfied.
Regarding the +'0', since n%10 produces an integer result and in putchar you are printing a char , you need to convert the integer to a char. This is done by adding the ascii value of 0 to the integer.
In C, there is no separate boolean type; an expression like a > b evaluates to zero if false, non-zero if true. Sometimes you can take advantage of this when testing for zero or non-zero in an int.
As for the '0', that just performs character arithmetic so that the right character is printed. The zero character has an ASCII encoding value which isn't zero, so the n value is used as an offset from that encoding to get the right numeric digit printed out.