开发者

Right shift two's complement number like an unsigned int

Is this possible? I have a signed int and need to shift it right 4 places. I cannot cast the int to an unsigned int, shift and then cast back. I need to deal with it after.

So if I have a bit sequence like:

x = 1001

and need to shift it right 2 spots:

x = x >> 2;

I get 1110;

I would like to get 0010. I cant think of a way to use and's and or's to do this. Any ideas?

Specifically this is what I need.

0x12345678 replace 56 with 0xab and end up with this: 0x1234ab78

My method was get the right of 56,

int right = Ox12345

get the left of 56

int left = Ox 78

get 56

int replace = 56

return right | left | replace

and return

Ox1234ab78

Im running into is开发者_运维问答sues if the number to the left of the replacement has a 1 as the MSB. Because I shift the entire thing left and then right and its transfers the 1 all the way through.


Another solution, since I remember doing a similar assignment in high-school where we were not allowed to use large hex numbers would be as follows:

x = (x >> 2) & ~((1 << 31) >> 1). This gives the same answer as my other answer, but takes away the need for the large hex number.


You can do x = (x >> 2) & 0x3FFFFFFF (assuming you're talking about 32-bit integers). This will set the 2 highest order bits to 0.

Edit:

Seeing the change in your problem, instead of your method, you can do something like this:

int result;
int start = 0x12345678, replace = 0xab;
result = (start & ~0xFF00) | (replace << 8);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜