Golang位运算以及一般字节操作

huangapple go评论86阅读模式
英文:

Golang bitwise operations as well as general byte manipulation

问题

我有一些在C#中执行一些位操作的代码。我正在尝试在Golang中做同样的操作,但遇到了困难。

以下是C#的示例代码:

byte a, c;
byte[] data; 
int j;
c = data[j];
c = (byte)(c + j);
c ^= a;
c ^= 0xFF;
c += 0x48;

我了解到Golang不能对byte类型执行位操作。因此,我需要将代码修改为uint8类型才能执行这些操作吗?如果是这样,是否有一种干净、正确/标准的实现方式?

英文:

I have some c# code that performs some bitwise operations on a byte. I am trying to do the same in golang but am having difficulties.

Example in c#

byte a, c;
byte[] data; 
int j;
c = data[j];
c = (byte)(c + j);
c ^= a;
c ^= 0xFF;
c += 0x48;

I have read that golang cannot perform bitwise operations on the byte type. Therefore will I have to modify my code to a type uint8 to perform these operations? If so is there a clean and correct/standard way to implement this?

答案1

得分: 12

Go确实可以对byte类型进行位运算,它只是uint8的别名。我需要对你的代码做以下更改:

  1. 变量声明的语法。
  2. 在将j添加到c之前,将其转换为byte,因为Go在进行算术运算时缺乏(按设计)整数提升转换。
  3. 移除分号。

以下是修改后的代码:

var a, c byte
var data []byte
var j int
c = data[j]
c = c + byte(j)
c ^= a
c ^= 0xFF
c += 0x48

如果你计划在Go中进行位非运算,请注意该运算符是^,而不是大多数其他现代编程语言中使用的~。这是用于异或运算的相同运算符,但两者不会产生歧义,因为编译器可以通过确定^是作为一元运算符还是二元运算符来区分它们。

英文:

Go certainly can do bitwise operations on the byte type, which is simply an alias of uint8. The only changes I had to make to your code were:

  1. Syntax of the variable declarations
  2. Convert j to byte before adding it to c, since Go lacks (by design) integer promotion conversions when doing arithmetic.
  3. Removing the semicolons.

Here you go

var a, c byte
var data []byte
var j int
c = data[j]
c = c + byte(j)
c ^= a
c ^= 0xFF
c += 0x48

If you're planning to do bitwise-not in Go, note that the operator for that is ^, not the ~ that is used in most other contemporary programming languages. This is the same operator that is used for xor, but the two are not ambiguous, since the compiler can tell which is which by determining whether the ^ is used as a unary or binary operator.

huangapple
  • 本文由 发表于 2014年6月8日 20:01:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/24105938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定