英文:
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
的别名。我需要对你的代码做以下更改:
- 变量声明的语法。
- 在将
j
添加到c
之前,将其转换为byte
,因为Go在进行算术运算时缺乏(按设计)整数提升转换。 - 移除分号。
以下是修改后的代码:
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:
- Syntax of the variable declarations
- Convert
j
tobyte
before adding it toc
, since Go lacks (by design) integer promotion conversions when doing arithmetic. - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论