Golang bitwise operations as well as general byte manipulation

11,920

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.

Share:
11,920
John
Author by

John

Updated on June 04, 2022

Comments

  • John
    John about 2 years

    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?

  • John
    John about 10 years
    Thanks. I had assumed because I could not perform bitwise operations on a []byte of length 1 that it was not possible and could only do it on unsigned ints.
  • Ken Bloom
    Ken Bloom about 10 years
    @john No bitwise operations on slices, even if they are of length 1. This isn't R or MATLAB where a scalar is the same as a vector of length 1.