Aug 13, 2012 at 11:58am UTC
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?
Aug 13, 2012 at 12:19pm UTC
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.
Aug 13, 2012 at 1:16pm UTC
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 Aug 13, 2012 at 1:16pm UTC
Aug 13, 2012 at 1:22pm UTC
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 Aug 13, 2012 at 1:45pm UTC
Aug 13, 2012 at 2:30pm UTC
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 Aug 13, 2012 at 2:31pm UTC
Aug 13, 2012 at 3:56pm UTC
@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.