Golang bitwise operations as well as general byte manipulation

只愿长相守 提交于 2019-12-06 03:38:55

问题


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:


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.



来源:https://stackoverflow.com/questions/24105938/golang-bitwise-operations-as-well-as-general-byte-manipulation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!