itsnani
itsnani

Reputation: 37

Could anyone please explain me this function, I am not able to understand this

   unsigned long fileSize = file.size();
   byte buf[4];
   buf[0] = (byte) fileSize & 0xFF;
   buf[1] = (byte) (fileSize >> 8) & 0xFF;
   buf[2] = (byte) (fileSize >> 16) & 0xFF;
   buf[3] = (byte) (fileSize >> 24) & 0xFF;  
   

can anyone explain me this code.assuming a file with a size of your choice

Upvotes: 1

Views: 147

Answers (5)

Igor G
Igor G

Reputation: 2361

Supposing you wanted to split a decimal number 8375 into digits. You could do it this way:

unsigned     value = 8375;
unsigned     digit_0 =  value         % 10;  // Gives 5
unsigned     digit_1 = (value /   10) % 10;  // Gives 7
unsigned     digit_2 = (value /  100) % 10;  // Gives 3
unsigned     digit_3 = (value / 1000) % 10;  // Gives 8

Well, the code you posted does just that. Only it splits the number into octets which are pairs of hexadecimal digits. I.e. every octet can take values in the range [0..255].

And the posted code uses bitwise operations: (a >> 8) is actually (a / 256), and (a & 0xFF) is (a % 256).

Upvotes: 3

0___________
0___________

Reputation: 67476

on little endian system it the same as:

memcpy(buf, &fileSize, 4);

or

union 
{
   unsigned long filesize;
   unsigned char buff[4];
}x = {.filesize = file.size());

Upvotes: -1

Remy Lebeau
Remy Lebeau

Reputation: 595392

The code is taking the lower 4 bytes of the file size (unsigned long may be 4 or 8 bytes, depending on platform/compiler), and is storing those 4 individual bytes into the buf array in little-endian byte order.

It takes the lowest 8 bits of fileSize and stores them into buf[0], then takes the next-lowest 8 bits and stores them into buf[1], and so on for buf[2] and buf[3].

Upvotes: 3

Rahul Agrawal
Rahul Agrawal

Reputation: 11

The program is storing the four bytes of an unsigned long integer into another byte array. The statement buf[0] = (byte) fileSize & 0xFF; performs a bit-masking and hence the last 8 bits are extracted from the unsigned long number. To extract further 8 bits, we shift the number right 8 bits and then again perform the bit-masking and so on.

Upvotes: 1

Carlos
Carlos

Reputation: 6021

This is simply finding the 4 bytes of a 4-byte integer. It's doing in hex what you'd do to find [2,0,2,0] from 2020.

The way it does it is by shifting the bits and using AND with a mask of all 1s.

Upvotes: 0

Related Questions