Bitwise Shifting in C
I've recently decided to undertake an SMS开发者_运维百科 project for sending and receiving SMS though a mobile.
The data is sent in PDU format - I am required to change ASCII characters to 7 bit GSM alphabet characters. To do this I've come across several examples, such as http://www.dreamfabric.com/sms/hello.html
This example shows Rightmost bits of the second septet, being inserted into the first septect, to create an octect.
Bitwise shifts do not cause this to happen, as >> will insert to the left, and << to the right. As I understand it, I need some kind of bitwise rotate to create this - can anyone tell me how to move bits from the right handside and insert them on the left?
Thanks,
Here is a quick algorithm to do that:
int b1, bnext;
int mod;
int pand;
char *b; // this is your byte buffer, with message content
int blen; // this is your byte buffer length
char sb[160];
int totchars = 0;
b1 = bnext = 0;
for (int i=0; i < blen; i++) {
mod = i%7;
pand = 0xff >> (mod + 1);
b1 = ((b[i] & pand) << mod) | bnext;
bnext = (0xff & b[i]) >> (7 - mod);
sb[totchars++] = (char)b1;
if (mod == 6) {
sb[totchar++] = (char)bnext;
bnext = 0;
}
}
sb[totchar] = 0;
It will convert 7bit compressed buffers to regular ASCII char arrays in C.
can anyone tell me how to move bits from the right handside and insert them on the left?
There are indirect ways in C but I'd simply do it like this:
void main()
{
int x = 0xBAADC0DE;
__asm
{
mov eax, x;
rol eax, 1;
}
}
This will rotate (not shift!) the bits to the left (one step). "ror" will rotate to the right.
精彩评论