Difference in results of bitwise shift calculations

WBOY
Release: 2024-02-08 21:11:13
forward
1009 people have browsed it

Difference in results of bitwise shift calculations

php editor Zimo brings you an article about "The difference in bitwise shift calculation results". In computer programming, bit shift operation is a common operation, which can perform left or right shift operations on binary numbers. However, different programming languages ​​may have differences in processing the results of displacement operations, which requires developers to pay attention. This article will introduce in detail the differences in the results of displacement operations in different programming languages, and provide some examples to help readers better understand and apply displacement operations. Whether you are a beginner or a developer with some programming foundation, you can get useful knowledge and skills from this article.

Question content

There are differences in the output of my go program, specifically the variables x1 and x2. Here is the relevant code snippet:

package main

var n uint = 10
const N uint = 10

func main() {
    var x1 byte = (1 << n) / 100
    var x2 byte = (1 << N) / 100
    println(x1, x2)
}
Copy after login

Expected output: 10 10

Actual output: 0 10

Be curious about the reasons behind the differences and seek explanations.

Solution

Constant expressions are evaluated with unspecified precision. Everything assigned to x2 is constant, so it correctly computes 210 / 100 = 1024 / 100 = 10. Whereas in the first expression, 1 is treated as byte, which means it is shifted out immediately. 1 must be treated as byte in Specification:

If the left operand of a non-const shift expression is an untyped constant, it is first implicitly converted to the type assumed when the shift expression is replaced only by its left operand.

1 is the untyped constant on the left and n is var making the expression non-const, so 1 must have its assignee x1 Type, i.e. byte.

The above is the detailed content of Difference in results of bitwise shift calculations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!