Why does it look like this in hexadecimal?

I am trying to do arithmetic bits with aand variables b. When I drop a, which has a value of 0xAF, the result is displayed as 8 digits. Unlike others, which show as 2 digits.

I don’t know why this is happening, but guess what it has to do %xwith showing the way and a little endian?

Here is my code:

#include <stdio.h>
int main()
{
    int a = 0xAF; // 10101111
    int b = 0xB5; // 10110101

    printf("%x \n", a & b); // a & b = 10100101
    printf("%x \n", a | b); // a | b = 10111111
    printf("%x \n", a ^ b); // a ^ b = 00011010
    printf("%x \n", ~a); // ~a = 1....1 01010000
    printf("%x \n", a << 2);// a << 2 = 1010111100 
    printf("%x \n", b >> 3); // b >> 3 = 00010110 

    return 0;
}
+4
source share
2 answers

There are many potential problems in the code.

, int. , undefined/ , << >> .

, , , . uint32_t stdint.h.

, , uint8_t, char, short, bool .., , int, . , unsigned char uint8_t. , .

, , printf , . , , . , undefined, . , -, ( ), .


"" , , ~ printf, unsigned int, %x.

, - :

#include <stdio.h>
#include <inttypes.h>

int main()
{
    uint32_t a = 0xAF; // 10101111
    uint32_t b = 0xB5; // 10110101

    printf("%.8" PRIx32 "\n", a & b);  // a & b = 10100101
    printf("%.8" PRIx32 "\n", a | b);  // a | b = 10111111
    printf("%.8" PRIx32 "\n", a ^ b);  // a ^ b = 00011010
    printf("%.8" PRIx32 "\n", ~a);     // ~a = 1....1 01010000
    printf("%.8" PRIx32 "\n", a << 2); // a << 2 = 1010111100 
    printf("%.8" PRIx32 "\n", b >> 3); // b >> 3 = 00010110 

    return 0;
}
+4

, int a, , 32-, a :

int a = 0xAF; // 0000 0000 0000 0000 0000 0000 1010 1111

, ,

1111 1111 1111 1111 1111 1111 0101 0000

,

0xFFFFFF50

, . 2 , , .

---- @chqrlie ---- 8 ,

printf("%hhx \n", ~a); // ~a = 1....1 01010000 --> Output : 50

unsigned char (8 [ os, , ]).

+6

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


All Articles