Coder Coder - 1 month ago 16
C Question

How to fetch the '3 bits' field from the below mentioned string format

enter image description here

Hi,

Say i have string like "888820c8". How do i fetch that 3 bits in an int in c programming language?

UPDATE 1 -

This is what i was able to do

static const char* getlast(const char *pkthdr)
{
const char *current;
const char *found = NULL;
const char *target = "8888";
int index = 0;
char pcp = 0;

size_t target_length = strlen(target);
current = pkthdr + strlen(pkthdr) - target_length;

while ( current >= pkthdr ) {
if ((found = strstr(current, target))) {
printf("found!\n");
break;
}
current -= 1;
}

if(found)
{
index = found - pkthdr;
index += 4; /*go to last of 8188*/
}
printf("index %d\n", index);
/* Now how to get the next 3 bits*/

printf("pkthdr %c\n", pkthdr[index]);

pcp = pkthdr[index] & 0x7;
printf("%c\n", pcp);
return pcp;
}


Clearly i know the last part of my program is wrong and any inputs would be helpful. thanks!

Update 2:

Thanks pratik for the pointer.
Does the below code look good now?

static char getlast(const char *pkthdr)
{
const char *current;
const char *found = NULL;
const char *tpid = "8188";
int index = 0;
char *pcp_byte = 0;
char pcp = 0;
int pcp2 = 0;
char byte[2] = {0};
char *p;
unsigned int uv =0 ;

size_t target_length = strlen(tpid);
current = pkthdr + strlen(pkthdr) - target_length;
//printf("current %d\n", current);

while ( current >= pkthdr ) {
if ((found = strstr(current, tpid))) {
printf("found!\n");
break;
}
current -= 1;
}

found = found + 4;

strncpy(byte,found,2);
byte[2] = '\0';

uv =strtoul(byte,&p,16);

uv = uv & 0xE0;
char i = uv >> 5;
printf("%d i",i);
return i;
}

Answer

The code that you have locates the character that contains the 3 bits that you want. That character will be a digit ('0' thru '9'), an uppercase letter ('A' thru 'F') or a lowercase letter ('a' thru 'f'). So the first task is to convert the character to its numeric equivalent, e.g. like this

unsigned int value;
if ( sscanf( &pkthdr[index], "%1x", &value ) != 1 )
{
    // handle error: the character was not a valid hexadecimal digit
}

At this point, you have a 4-bit value, but you want to extract the upper three bits. That can be done with shifting and masking, e.g.

int result = (value >> 1) & 7;
printf( "%d\n", result );

Note that if you want to return the 3-bit number from the function, the function prototype needs to be changed to return an int, e.g.

static int getlast(const char *pkthdr)
{
    // ...
    return result;
}