Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

不同语言对于位移运算的规则 #35

Open
yankewei opened this issue Sep 23, 2020 · 0 comments
Open

不同语言对于位移运算的规则 #35

yankewei opened this issue Sep 23, 2020 · 0 comments

Comments

@yankewei
Copy link
Owner

yankewei commented Sep 23, 2020

位移运算我们都知道,这里说的是逻辑运算x << y,比如2 << 1的结果是4
y的值小于等于当前系统的位数是,好像都没有问题,但是当大于时,就会有不同的答案,下面以phpgoc这三个语言来做个例子:

<?php
$i = 2;
printf("\$i << 1 = %d\n", $i << 1); // 2 << 1 = 4
printf("\$i << 64 = %d\n", $i << 64); // 2 << 64 = 0
printf("\$i << 65 = %d\n", $i << 65); // 2 << 65 = 0

php没有报错,就是直接返回了0。

package main

import "fmt"

func main() {
	i := 2
	fmt.Printf("i << 1 = %d\n", i<<1)   // i << 1 = 4
	fmt.Printf("i << 64 = %d\n", i<<64) // i << 64 = 0
	fmt.Printf("i << 65 = %d\n", i<<65) // i << 65 = 0
}

go语言没有报错,会直接返回0。

#include <stdio.h>

int main()
{
    int i = 2;
    printf("i << 1 = %d\n", i << 1); // i << 1 = 4
    printf("i << 64 = %d\n", i << 64); // i << 64 = 2
    printf("i << 65 = %d\n", i << 65); // i << 65 = 4
}

c语言会对值取模,在位移。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant