简体   繁体   English

谁能给我解释一下这个 function,我无法理解

[英]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 .该代码采用文件大小的低 4 字节( unsigned long可能是 4 或 8 字节,具体取决于平台/编译器),并以小端字节顺序将这 4 个单独的字节存储到buf数组中。

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] .它获取fileSize的最低 8 位并将它们存储到buf[0]中,然后获取次低的 8 位并将它们存储到buf[1]中,对于buf[2]buf[3]依此类推。

Supposing you wanted to split a decimal number 8375 into digits.假设您想将十进制数 8375 拆分为数字。 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].即每个八位位组都可以取 [0..255] 范围内的值。

And the posted code uses bitwise operations: (a >> 8) is actually (a / 256) , and (a & 0xFF) is (a % 256) .发布的代码使用按位运算: (a >> 8)实际上是(a / 256)(a & 0xFF)(a % 256)

The program is storing the four bytes of an unsigned long integer into another byte array.该程序将 unsigned long integer 的四个字节存储到另一个字节数组中。 The statement buf[0] = (byte) fileSize & 0xFF;语句buf[0] = (byte) fileSize & 0xFF; performs a bit-masking and hence the last 8 bits are extracted from the unsigned long number.执行位掩码,因此从无符号长数中提取最后 8 位。 To extract further 8 bits, we shift the number right 8 bits and then again perform the bit-masking and so on.为了进一步提取 8 位,我们将数字右移 8 位,然后再次执行位屏蔽等。

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.这只是找到 4 字节 integer 的 4 个字节。它以十六进制表示,就像您从 2020 年开始查找 [2,0,2,0] 一样。

The way it does it is by shifting the bits and using AND with a mask of all 1s.它的实现方式是移动位并使用 AND 和全 1 的掩码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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