Command line and bit operations in C

There is a code. How to run it via the command line, as it is done in general. The program itself must swap the two specified bytes of the number and take the data from the command line and output it there (is everything correct in the code?)

#include <stdio.h>
#include <conio.h>

int main(int args, char** argv[]){
    unsigned b, a;
    int x = atoi(argv[1]), y = atoi(argv[2]);
    unsigned long long num = atoll(argv[3]);
    change(x-1,y-1, num);
}

void change(int x, int y, long long z) {
    //значение байта на позиции x
    long long bx = 0xFF & (z >> (8 * x));
    long long by = 0xFF & (z >> (8 * y));
    //маска содержит нули на позициях x и y
    long long mask = ~(((long long) 0xFF << (8 * x)) | ((long long)0xFF << (8 * y)));
    //обнулили эти позиции
    z &= mask;
    //и заполнили нужными значениями
    z = z | (bx << (8 * y)) | (by << (8 * x));
    printf("%llx\n", z);
}
Author: Harry, 2019-04-06

1 answers

How else can I determine the position of the highest unit in the bitmap a performance ?

Approximately so:

#include <stdio.h>
#include <stdlib.h>

/*
  Определяет позицию самой левой единицы в двоичном представлении числа.

  n - Проверяемое число

  return:
    0...31 - Позиция самой левой обнаруженной единички
    -1 Число равно 0
*/ 

int left_one_position(int n) {
    int j;

    for(j=31; j>=0; j--) {
        if (n & 0x80000000) return j;
        n = n<<1;
    }
    return -1;
}

/*
  Главная функция программа
*/
int main(int argc, char *argv[]) {

    int test_val;
    int position;

    if (argc != 2) {
        printf("Неверные параметры командной строки\n");
        return -1;
    }

    test_val = atoi(argv[1]);
    position = left_one_position(test_val);

    printf("В слове %08x самая левая единица в позиции %5d\n", test_val, position);
}
 1
Author: Sergey, 2019-04-08 02:40:20