1

I'm attempting to write a program which takes a string input of '0' and '1' from the user and then uses that given string to change each bit of another variable.

i.e.

char input[20];
unsigned short bits = 0;

printf("Enter a binary string of 16 bits.\n");

fgets(input, 20, stdin);
input[strlen(input) - 1] = '\0';

is what I have to get and store a two byte string from the user. I then want to take that string and manipulate the variable 'bits' to match what was entered.

So if the user entered 10011001 10011001 I would like to change the value of 'unsigned short bits' from all 0's to the matching value in binary.

My thinking right now is that I could loop through the input string and left shift 'bits' with each pass but as far as I know left shifting will always drop the left most bit and add a 0 as the right most bit. Is there a way to add a 1 as the left most bit with some bitwise command I don't know of so that if the loop sees a '1' in the string it adds a one to the rightmost bit?

nontype
  • 25
  • 6
  • For each char of the string, shift `unsigned short bits` left and set bit 0 to the value in the string. If the input has fewer bits than needed it still works. – Weather Vane Nov 24 '19 at 20:28
  • I don't think `input[strlen(input) - 1] = '\0';` is correct. – LegendofPedro Nov 24 '19 at 20:30
  • Deleted my previous comment because I think I misread your question. However is "add a 1 as the left most bit" a typo? Did you mean "right" here? – Edd Inglis Nov 24 '19 at 20:30
  • 1
    @LegendofPedro it can be but is not guaranteed to work. Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane Nov 24 '19 at 20:31
  • 1
    @WeatherVane that's good info. I was thinking about what happens if you pipe `echo ""` and have a zero-length input string without a newline. – LegendofPedro Nov 24 '19 at 20:38
  • @LegendofPedro similarly the last line of a redirected file might not end with newline. – Weather Vane Nov 24 '19 at 20:43
  • Aside, consider what happens when the first character entered is a _null character_. `input[strlen(input) - 1]` becomes a hacker exploit. – chux - Reinstate Monica Nov 24 '19 at 23:44

2 Answers2

2

Use bits = (bits << 1); to shift in a 0. Use bits = (bits << 1) | 1; to shift in a 1.

LegendofPedro
  • 1,393
  • 2
  • 11
  • 23
  • This worked! thank you and everyone else for the quick replies. I was almost there but I was using OR incorrectly in my loop. – nontype Nov 24 '19 at 20:34
1

That would work.

In your loop, you first shift bits to the left and then OR 1 if the character is 1:

bits |= 1;
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27