简体   繁体   中英

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

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] .

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. Ie 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) .

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.

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM