idea for byte circelize

Hi
I try to write a function in C that get one byte(char) and a number N(integer) and it needs to shift left N times and return the new number

exemple:
0xc6 // 1100 0110
N=1
0x8D // 1000 1101 after circlized left one time

the prototype is
char encodeChar(char d, int n)

can anyone give me a idea how to start?
Use the bitwise operators << and >>. The only issue is that it won't "circle" the end values so you have to figure that one out on your own (really easy to do once you realize what's going on. Remember, a byte is still just a number (binary) that can manipulated like any other number.
Try the following sample code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <iomanip>
#include <limits>

int main()
{
	const/*expr*/ unsigned char HIGH_BIT = 1 << std::numeric_limits<unsigned char>::digits - 1;
	unsigned char c = '\xC6';

	std::cout << std::hex << ( int )c << std::endl;

	c = bool( c & HIGH_BIT ) + ( c << 1 );

	std::cout << std::hex << ( int )c << std::endl;
}


The expression statement

c = bool( c & HIGH_BIT ) + ( c << 1 );

can be used inside a loop if you have to shift more than one position.
Last edited on
1
2
3
4
5
unsigned char encodeChar(char d, int n) {
	char overflow = d >> (sizeof(d) * 8 - n);

	return (d << n) | overflow;
}


I had this in mind. However, the solution from vlad is another way to go.
Last edited on
Thanks i got it!

1
2
3
4
5
6
7
char encodeChar(char d){
       char tmp = d;
       d << N;
       tmp >> 8-N;
       d |= tmp;
       return d;
}
I think you meant
1
2
3
4
5
6
7
char encodeChar(char d){
       char tmp = d;
       d <<= N;
       tmp >>= 8-N;
       d |= tmp;
       return d;
}
Last edited on
@viliml

I think that your code is incorrect because the type char can be signed and in this case the sign bit can be copied when the shift right operation is executed.
Topic archived. No new replies allowed.