Home >Backend Development >Golang >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.
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) }
Expected output: 10 10
Actual output: 0 10
Be curious about the reasons behind the differences and seek explanations.
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!