Reading input using getchar_unlocked() - c

I have learnt that using getchar_unlocked is fast way of reading input. I have seen the code to read at many places but was unable to understand. Can anyone please help me understand how to read using getchar_unlocked ?
Thanks in Advance.
void scanint(int &x)
{
register int c = getchar_unlocked();
x = 0;
for(;(c<48 || c>57);c = getchar_unlocked())
;
for(;c>47 && c<58;c = getchar_unlocked())
{
x = (x<<1) + (x<<3) + c - 48;
}
}
I have seen many other codes as well. I dont particularly understand the purpose of shifting the number. Any help regarding that is appreciated

getch_lock reads a character at a time. here in the given code we are trying to read an integer. the purpose of first for loop is to read digit character if any present and neglect it. The second for loop reads a char which must be digit and performs
n=n*10+c
As C is in Ascii we have subtracted 48 ie Ascii code of '0' . To make code faster instead of using multiplication shift is used.
n*10=n*(8+2)=n*8+n*2=n<<3+n<<1

getchar_unlocked() is like getchar() except that it does not check for multi-thread locks.
So, it is faster, but it is not thread-safe.

I think you might have the wrong idea of the purpose of getchar_unlocked(). Really.
When doing single-character I/O from a human user, it's fantastically hard to believe that you need to focus on being "fast", since the human will be very slow.
The function you included looks like it's reading an integer using getchar_fast(), and is written in a pretty horrible style. It certainly doesn't look like part of a solution to anything in particular. It's also totally broken in its handling of the x pointer variable.
In short, your question is not very clear.

Related

Having trouble understanding output of line of code -

I don't understand the use of return 0* statement??
Tried looking for answers on Google
return 0*printf("%d",a[i]);
I don't understand the outcome.
As for me then this
return 0*printf("%d",a[i]);
just a bad programming style.
At least it would be better to write instead
return ( printf("%d",a[i]), 0 );
not saying about
printf("%d",a[i]);
return 0;
Maybe this statement is found in a recursive function.
As for your question
Having trouble understanding output of line of code -
then this line outputs the value of the i-th element of the integral array a and exits the corresponding function.
TL/DR - it's writing the value of a[i] to standard output, multiplying the number of characters written by 0, and returning the result...which is always 0.
I'd like to see the rest of the code for context - based on this single line of code it doesn't make sense, but maybe in context it would look a little less nonsensical.
printf returns the number of characters (bytes) written to the output stream, so this is writing the value of a[i] to standard output, multiplying the number of characters written by 0, and returning the result ... which is always 0, so again, this line in isolation doesn't make a ton of sense.
I'm hard-pressed to think of a use case where this would be logical, but that doesn't mean there isn't one. Perhaps the author wants to make sure the value of a[i] gets displayed even in the event of an error, but why not just do
if ( error_occurred )
{
printf( "%d", a[i] );
return 0;
}
in that case?
It could be the author intends the print statement to be executed concurrent with the return, in which case they don't understand how C works. It could be the author confuses terse code with fast code, in which case they still don't understand how C works.
Or maybe the author is being tricky for tricky's sake.

How do I read this software phase lock loop code?

In my search for an example of a software phase lock loop I came across the following question
Software Phase Locked Loop example code needed
In the answer by Adam Davis a site is given that is broken and I have tried the new link that is given in a comment but I cant get that to work either.
The answer from Kragen Javier Sitaker gave the following code as a simple example of a software phase locked loop.
main(a,b){for(;;)a+=((b+=16+a/1024)&256?1:-1)*getchar()-a/512,putchar(b);}
Also included in his answer was a link to what should be a much more readable example but this link is also broken. Thus I have been trying to translate the above code into simpler and more readable code.
I have come this far:
main(a,b){
for(;;){
// here I need to break up the code somehow into a if() statement('s).
if(here I get lost){
a = a+1;
if(here i get lost some more){
b = b+1;
}
}
}
Thanks to the SO question What does y -= m < 3 mean?
I know it is possible to break up the a+= and b+= into if statements.
But the (&256? 1 : -1)*getchar()-a/512,putchar(b); part in the code is killing me. I have been looking on Google and on SO to the meaning of the symbols and functions that are used.
I know the & sign indicates an address in memory.
I know that the : sign declares a bit field OR can be used in combination with the ? sign which is a conditional operator. The combination of the two I can use like sirgeorge answer in what does the colon do in c?
Theory Behind getchar() and putchar() Functions
I know that getchar() reads one character
I know that putchar() displays the character
But the combination of all these in the example code is not readable for me and . I can not make it readable for my self even do I know what they all separately do.
So my question: How do I read this software phase lock loop code?
main(a,b){for(;;)a+=((b+=16+a/1024)&256?1:-1)*getchar()-a/512,putchar(b);}
What I get is:
main (a, b)
{
char c;
for (;;)
{
c = getchar();
b = (b + 16 + (a / 1024));
if(!(b & 256))
{
c = c * -1;
}
a = a + c - (a/512);
putchar(b);
}
}
I had to add a c variable to not get lost.
What the program does:
Take a and b.
Infinite loop:
get a char input in c
calculate b
If (b bitwise AND 256)
c = -c
Calculate a
Print b
It seems it translate input into something else, I have to see the code in action to understand better myself.
Hope it helped!
Hint:
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
a+= => a = a +
a?b:c => if(a){return b;} else {return c;} (As a function itself, it don t truly return)
Add parentheses, it help.
a & b is bitwise AND:
a/b |0|1|
0|0|0|
1|0|1|

Lower cpu usage on searching a big char array

I'm searching for few bytes in a char array. The problem is that on slower machines the process gets up to 90%+ cpu usage. How to prevent that? My code is:
for(long i = 0; i < size - 5; ) {
if (buff[++i] == 'f' && buff[++i] == 'i' && buff[++i] == 'l' && buff[++i] == 'e') {
printf("found at: %d\n", i);
}
}
EDIT:
The string "file" is not null-terminated.
This looks like an attempt at very naive string search, I'd suggest you use either the standard functions provided for this purpose (like strstr) and/or research string search algorithms like Boyer-Moore.
The linked Wikipedia article on Boyer-Moore shows quite well why moving along one character at a time on a mismatch (like you do) is not necessary - it's an interesting read.
EDIT: also look at this page, it has a nice animated presentation that shows how BM does its job.
EDIT2: regarding the string not being nullterminated: either you
buff[size] = 0;
terminate it yourself, and use strstr, or you have a look at the BM code from the page I linked, that works with lengths, ie it will work with strings without terminating 0.
There is nothing wrong with getting 90% utilisation, since the algorithm is CPU-bound. But...
Unless you expect the search term to be on a 32-bit word boundary, the code is broken. If the word 'file' begins on the second character of the buffer, you will simply skip over it. (EDIT: Short-circuit eval means the code is correct as it stands. My mistake.)
Don't roll your own code for this; use strstr.
Try just storing a list of values where 'file' is found and print them out after the loop. It will prevent context switches and will enable the CPU to use the cache better. Also put i in a register.

Converting ASCII string to integer using bitwise operators in C & vice versa

I am able to do this without using bitwise operators as below
int AsciiToInteger()
{
char s[] = "Stack Overflow";
int i, n = 0;
for (i = 0; s[i] !='\0'; i++)
{
n += s[i];
}
return n;
}
How can I achieve the same using bitwise operators in C without using for loop?
You can achieve the same without a for loop using recursion:
int AsciiToInteger(const char * Str)
{
if(*Str)
return (int)*Str + AsciiToInteger(Str+1);
else
return 0;
}
/* ... */
int n = AsciiToInteger("Stack Overflow");
I don't know what bitwise operators have to do with this, you surely cannot use only them without a loop and without recursion for arbitrary-length strings (for fixed length strings instead the result would probably be something like unrolling the loop).
... but now that I read the comments I'm quite sure I didn't get the sense of the question... :S
Except as an exercise in building higher level operations from bitwise operations, the task you're trying to accomplish is foolish. Don't do it.
As an exercise, the most important thing to realize is that you don't have to go back to the start every time you need to implement something new in terms of the building blocks. Instead you could write addition and subtraction functions in terms of bitwise building blocks, and put those together using the existing higher-level algorithm you've already got.
As for eliminating the loop, you could just unroll it to support a fixed max number of digits (the longest value that will fit in int, for example) unless you need to support arbitrary number of leading zeros. Recursion is a very bad approach in general and contrary to the whole "close to the metal" aspect of this exercise. Perhaps they just want you to avoid adding/incrementing a counter in the loop with "high level" addition, in which case you could use your bitwise adder function...
One of the main reasons that loops exist is so that you can do operations an unknown number of times. If you don't know how long your string is, you have no way of doing this without a loop. Even if you do know the length of the string, why would you want to do it without a loop?

is it possible to write a program which prints its own source code utilizing a "sequence-generating-function"

is it possible to write a program which prints its own source code utilizing a "sequence-generating-function"?
what i call a sequence-generating-function is simply a function which returns a value out of a specific interval (i.e. printable ascii-charecters (32-126)). the point now is, that this generated sequence should be the programs own source-code. as you see, implementing a function which returns an arbitrary sequence is really trivial, but since the returned sequence must contain the implementation of the function itself it is a highly non-trivial task.
this is how such a program (and its corresponding output) could look like
#include <stdio.h>
int fun(int x) {
ins1;
ins2;
ins3;
.
.
.
return y;
}
int main(void) {
int i;
for ( i=0; i<size of the program; i++ ) {
printf("%c", fun(i));
}
return 0;
}
i personally think it is not possible, but since i don't know very much about the underlying matter i posted my thoughts here.
i'm really looking forward to hear some opinions!
If you know how to encode an array as a function (you seem to be saying you already know how to do this) then the Kleene Recursion theorem guarantees it can be done.
But for doubting Thomases, here's a C example. It has a program generating function that uses only +, -, *, / or calls other functions that use them.
Quines are always possible if you have Turing completeness and freedom to print what you like.
What you're referring to is a QUINE. Wiki's article on it is pretty good, with some helpful links. http://en.wikipedia.org/wiki/Quine_%28computing%29
To fly off at a tangent, try looking at Tupper's Self-Referential Formula.

Resources