What happen when we do AND operation of 4 byte number with 2 byte number

2

I am trying to write a piece of code to extract every single byte of data out of a 4 byte integer
after little bit of searching i actually found the code with which this can be achieved , but i am just curious to know why it behaves the way output is created , below is the code

#include <stdio.h>

int getByte(int x, int n);

void main()
{
    int x = 0xAABBCCDD;
    int n;

    for (n=0; n<=3; n++) {
        printf("byte %d of 0x%X is 0x%X\n",n,x,getByte(x,n));
    }

}

// extract byte n from word x
// bytes numbered from 0 (LSByte) to 3 (MSByte)
int getByte(int x, int n)
{
    return (x >> (n << 3)) & 0xFF;
}

Output:

byte 0 of 0xAABBCCDD is 0xDD
byte 1 of 0xAABBCCDD is 0xCC
byte 2 of 0xAABBCCDD is 0xBB
byte 3 of 0xAABBCCDD is 0xAA

the result is self explanatory but why the compiler didn't converted 0xFF into 0x000000FF , since it has to perform AND operation with a 4 byte number and instead generated the output consisting of only 1 byte of data and not 4 byte of data.

c
bit-manipulation
bitwise-operators
asked on Stack Overflow Dec 8, 2017 by beastboy • edited Dec 8, 2017 by Ken Y-N

3 Answers

4

The compiler did convert 0xFF to 0x000000FF. Since the value is an integer constant, 0xFF gets converted internally to a 32-bit value (assuming that your platform has a 32-bit int).

Note that the values you get back, i.e. 0xDD, 0xCC, 0xBB, and 0xAA, are also ints, so they have leading zeros as well, so you actually get 0x000000DD, 0x000000CC, and so on. Leading zeros do not get printed automatically, though, so if you wish to see them, you'd need to change the format string to request leading zeros to be included:

for (n=0; n<=3; n++) {
    printf("byte %d of 0x%08X is 0x%08X\n", n, x, getByte(x,n));
}

Demo.

answered on Stack Overflow Dec 8, 2017 by Sergey Kalinichenko • edited Dec 12, 2017 by Sergey Kalinichenko
3

The output is a 4-byte number, but printf("%X") doesn't print any leading zero digits.

If you do printf("foo 0x%X bar\n", 0x0000AA) you'll get foo 0xAA bar as output.

answered on Stack Overflow Dec 8, 2017 by Dai
1

0xFF and 0x000000FF are both exactly the same thing, by default the formatting will drop the leading 0's if you want to print them in your output, you just need to specify it:

printf("byte %d of 0x%X is 0x08%X\n",n,x,getByte(x,n));

But since you are printing Bytes I'm not quite sure why you would expect the leading 0's.

answered on Stack Overflow Dec 8, 2017 by smsisko

User contributions licensed under CC BY-SA 3.0