S
S
Serverprom2015-04-19 14:35:28
.NET
Serverprom, 2015-04-19 14:35:28

How to perform a right bit rotation in C#?

Hello! I am writing a program in C#. There is a number that takes values ​​from 0 to 255 (type - Byte; 8 bits), in which you need to perform a cyclic bit shift to the right. Accordingly, after the shift, you should get a number from 0 to 255.
I found this code:

int shr(int a, int s) {
  return (a>>s) | (a<<32-s);
}

But it works in a strange way - it turns out numbers that are much larger than 255. Tell me how to implement this? Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Movchan, 2015-04-19
@Serverprom

a = (a>>s) | ((a<<(8-s)) & 255)

V
Vladimir Martyanov, 2015-04-19
@vilgeforce

Well of course they WILL exceed 255! First, the parameters and return value are int, and you need char. Secondly, the data length is explicitly specified as 32 bits.

M
Mrrl, 2015-04-19
@Mrl

((a*257)>>s)&255.
It will work faster, for some reason, logical operations in C # are very expensive compared to multiplication.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question