Golang按位操作以及一般字节操作 [英] Golang bitwise operations as well as general byte manipulation

查看:258
本文介绍了Golang按位操作以及一般字节操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些c#代码对一个字节执行一些按位操作。



在c#中的示例

在golang中做同样的事情,  byte a,c; 
byte [] data;
int j;
c = data [j];
c =(byte)(c + j);
c ^ = a;
c ^ = 0xFF;
c + = 0x48;

我读过golang无法对字节类型执行按位操作。因此,我将不得不修改我的代码到类型uint8来执行这些操作?如果是的话,是否有一个干净的,正确的/标准的方式来实现这一点?

解决方案

c $ c> byte 类型,它只是 uint8 的别名。我必须对您的代码进行的唯一更改是:
$ b


  1. 变量声明的语法

  2. 在将它添加到 c 之前,将 j 转换为 byte ,因为进行算术运算时,缺少整数提升转换。

  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中,请注意操作符为 ^ ,而不是在大多数其他当代编程语言中使用的。这与用于xor的操作符是相同的,但这两者并不是不明确的,因为编译器可以通过确定 ^ 是用作一元还是哪一个,二元运算符。


    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?

    解决方案

    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.

    这篇关于Golang按位操作以及一般字节操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆