Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scan input of bits from user

Tags:

c

i wanted to know what is the best way to scan a input of.. lets say 16 bits from user.(exp: [0 1 0 0 1 1 0 ...]) i will use short int for that.

lets say that everyone of the bits stand for some property. and i want that the user will be able to give me the input (some permutation of the the bits) by 2 ways:

first way: all of the 16 bits initialized with zero's, the user will give me the spots of the bits that he want to turn on:

short int a=0; (look like [000000....0])

lets say user choose 3, 5

so, i know i can make a mask initialized with zero exept the requested place (which will be 1) like this:

short int mask=0x1; mask<<=3;

a|=mask;

and after that same thing with a mask that represent the fifth bit. but is there a better way for doint that ?

the seconed question is, say i want to scan from the user the string that represent the requested permutation. (exp: 01101010100..) how should i do that ? the syntex is important to me here.. what should i write in the scanf ? etc. thanks a lot.

like image 523
user3250354 Avatar asked Jan 30 '14 10:01

user3250354


1 Answers

Since the syntax of the 2 inputs is different, allow both.

// pseudo code
fgets(buffer,...);
if (IsSyntax1(buffer)) {
  a = ProcesssPerSyntax1(buffer, a);
else if (IsSyntax2(buffer)) {
  a = ProcesssPerSyntax2(buffer, a);
else Error();

Example syntax parser

char *endptr;
// looking for 16-digit binary number
unsigned long tmp = strtoul(buffer, &endptr, 2);
if (endptr == &buffer[16] && *endptr == '\n') {
  a = (short) tmp;
}
else {
  // Search for comma separated 0-15 offsets
  char *p = buffer;
  unsigned mask = 0;
  do {
    unsigned long index = strtoul(p, &endptr, 10);
    if (index >= 16) return fail;
    if ((*endptr != ',') && (*endptr != '\n')) return fail;
    if (endptr == p) return fail;
    mask |= 1U << (unsigned) index; 
    p = endptr + 1;
  } while (*endptr == ',');
  a = mask;
}

[Edit]
Should use strtoul() vs. strtol() to deal with 16-bit int/unsigned as hinted by @BLUEPIXY comment.

like image 137
chux - Reinstate Monica Avatar answered Oct 12 '22 19:10

chux - Reinstate Monica