c++ - 在这里进行位移有什么意义?

标签 c++ c io bitwise-operators

我找到了这段用于快速 I/O 的代码。

    #include <cstdio>

inline void fastRead_int(int &x) {
    register int c = getchar_unlocked();
    x = 0;
    int neg = 0;

    for(; ((c<48 || c>57) && c != '-'); c = getchar_unlocked());

    if(c=='-') {
        neg = 1;
        c = getchar_unlocked();
    }

    for(; c>47 && c<58 ; c = getchar_unlocked()) {
        x = (x<<1) + (x<<3) + c - 48;
    }

    if(neg)
        x = -x;
}

inline void fastRead_string(char *str)
{
    register char c = 0;
    register int i = 0;

    while (c < 33)
        c = getchar_unlocked();

    while (c != '\n') {
        str[i] = c;
        c = getchar_unlocked();
        i = i + 1;
    }

    str[i] = '\0';
}

int main()
{

  int n;
  char s[100];

  fastRead_int(n);
    printf("%d\n", n);

  fastRead_string(s);
    printf("%s\n", s);
  return 0;
}

为什么会有位移 (x<<1) + (x<<3)?另外,当我们输入除否定和数字以外的字符时会发生什么?

最佳答案

Why is there a bitwise shift (x<<1) + (x<<3)?

左移n位相当于乘以2^n;所以这个表达式相当于乘以 10(因为 2^1 + 2^3 = 2 + 8 = 10)。

这样编写代码是因为相信 (a) 移位和加法比乘法快得多,并且 (b) 编译器不知道乘以 10 的最佳方法。对于大多数现代平台而言,这两种假设都是错误的,因此直接

x = x*10 + c - '0';    // '0' is more readable, and portable, than 48.

可能会更快并且更具可读性。

Also what's happening when we enter character other than neg and numbers?

第一个循环跳过除“-”和数字以外的任何内容;第二个在遇到非数字时停止(在从流中使用该字符之后)。因此它将返回它在输入流中找到的第一个十进制整数,如果没有则返回零。例如,如果输入是

xxxx123-456xxx-1234xxx

第一个调用将返回 123,第二个 456(因为 - 被第一个调用消耗),第三个 -1234,以及任何进一步调用 0

关于c++ - 在这里进行位移有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18061305/

相关文章:

c++ - GLSL 传递整数顶点属性

C++ 正则表达式和占位符

c - 关于锁定 fread/fwrite 并从不同进程调用

python - 为什么我不能在打开的文件上调用 read() 两次?

go - 在 Golang 中读取/复制从 `io.Reader` 到 `io.Writer` 的特定数量的字节,或者如果超过特定字节限制则返回错误?

c++ - syntax::function_name 在 C++ 中是什么意思?

c++ - 在套接字编程中发送额外的查询

带有内联函数的 const 参数

无法跳出 "While"循环

c - 为什么 C 使用星号来声明指针,而不是像 Pascal 那样使用插入符号?