3

If I want to bit shift the integer 5 by 3, so int a = 5; int b = a << 3;, the result would be 40 in decimal as 5 is 101 and 40 is 101000.

What if however, I have the following char array: 00000 00101 and by bit shifting three to the left, I want the result to be 00001 01000. So I want to accommodate for the 0's padding. What do you suggest?

2 Answers 2

3

If you meant an actual char array, you can use memmove() and memset():

char str[] = "0000000101";

int shift = 3;
int length = strlen(str);

memmove(str, str + shift,length - shift);
memset(str + length - shift,'0',shift);

//  Result:
//  "0000101000"
Sign up to request clarification or add additional context in comments.

8 Comments

You're shifting right, rather than left, and overflowing the array, because you memmove() length bytes, not length - shift.
Thanks, I saw your first comment and fixed it a few min. ago. EDIT: I'm shifting left. I've tested it.
Yes you are, I mentally flipped the order of src and dst in memmove. Your current code is correct.
I think OP wanted to shift by three bits. Can't do that with memmove.
@DanielFischer: It's not entirely clear what the OP wants. The way I'm reading it, the bits are stored as a char array where each char is either '0' or '1'. So it's unclear until the OP clarifies it.
|
1

Access the buffer with a 16-bit pointer, use htons to take care of endian issues

char c[2] = {0, 5};

uint16_t* p16 = (uint16_t*)c;

*p16 = htons((ntohs(*p16) << 3));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.