How can I safely and quickly extract numbers from int?

We currently have code for extracting numbers from int, but I need to convert it to a platform without snprintf, and I'm afraid that the buffer is overflowing. I started writing my own portable (and optimized) snprintf, but I was told to ask here if anyone had a better idea.

int extract_op(int instruction)
{ 
    char buffer[OP_LEN+1];
    snprintf(buffer, sizeof(buffer), "%0*u", OP_LEN, instruction);
    return (buffer[1] - 48) * 10 + buffer[0] - 48;
}

We use C lines because speed is very important.

+3
source share
5 answers

sprintf . sizeof type * 3 * CHAR_BIT / 8 + 2 - type. , , CHAR_BIT 8, . , ( ), .

+2

instruction ; " " :

int extract_op(unsigned int instruction)
{
    int first = 0;
    int second = 0;
    while(instruction) {
        second = first;
        first = instruction % 10;
        instruction /= 10;
    }
    return first + 10 * second;
}

, return , , : .

, , , , , , .

+7

, ... , "%0*u", OP_LEN , OP_LEN.

, OP_LEN , 10 ^ (OP_LEN-2)

#define DIVISOR ( (int) ( 1.e ## OP_LEN * 0.01 ) )

, @zneak,

int extract_op( int instruction )
{
    instruction /= DIVISOR;
    int tens = (instruction / 10) % 10;
    int units = instruction % 10;
    return units * 10 + tens;
}

#undef DIVISOR
+1

U u, . , . .

int a[5];

int extract_op(unsigned int instruction)
{
int i=0;    
int first = 0;
    int second = 0;
    while(instruction) {
        second = first;
        first = instruction % 10;
        instruction /= 10;
    }
    a[i]=first;
}

, , 5 . ,

0

should work also for 0 and <0.

int extract_op( int instruction )
{
  int numd = 1;
  while( instruction /= 10 )
    ++numd;
  return numd;
}
0
source

Source: https://habr.com/ru/post/1762401/


All Articles