Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang bitwise operations as well as general byte manipulation

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?

like image 599
John Avatar asked Jun 08 '14 12:06

John


People also ask

What is Bitwise manipulation used for?

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization.

Are Python Bitwise Operators faster?

Software Engineering Python Bitwise operators happen to be much simpler operators, making them quite a bit faster than arithmetic operators. Bitwise operators are most often used when encoding and decoding bits.

How do you identify a bit manipulation problem?

If a number N is a power of 2, then the bitwise AND of N and N-1 will be 0. But this will not work if N is 0. So just check these two conditions, if any of these two conditions is true. Refer check if a number is power of two for details.

What is bit clear operator?

That is literally " x AND (bitwise NOT of y )". In the arithmetic operators section of the spec describes &^ as a "bit clear" operation, which gives an idea of what you'd want to use it for. As two separate operations, ~y will convert each one bit to a zero, which will then clear the corresponding bit in x .


1 Answers

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.

like image 73
Ken Bloom Avatar answered Oct 05 '22 11:10

Ken Bloom