且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

exFAT校验和的计算

更新时间:2023-10-27 09:52:22

我怀疑这是运算符优先级的问题.

I suspect it's a problem of operator precedence.

此页面中,我看到了crc定义,其中 checksum 以此方式修改

In this page I see the crc definition where checksum is modified in this way

checksum = (checksum<<31) | (checksum>> 1) + data[i];

也就是说,如果我没记错的话,它等同于

that is, if I'm not wrong, equivalent to

checksum = (checksum<<31) | ((checksum>> 1) + data[i]);

因为(如果我记得很好),加号运算符( + )的优先级比位或运算符( | )大.

because (if I remember well) the plus operator (+) has a bigger precedence than the bit or operator (|).

相反,您的代码是

checksum = ((checksum << 31) | (checksum >> 1)) + (uint32_t) data[i];

这是完全不同的代码,因为您首先应用按位或,然后再应用加号.

that is a total different code because you first apply the bitwise or and next the plus.

我想可以和

checksum = (checksum << 31) | ((checksum >> 1) + (uint32_t) data[i]);

p.s .:对不起,我的英语不好

p.s.: sorry for my bad English

---编辑2016.06.09 ---

---EDIT 2016.06.09---

另一个问题应该是 data 的签名.

Another problem should be the signedness of data.

您将 data 定义为 char 的指针;ntfs.com将 data 定义为 const unsigned char 的数组.

You define data as a pointer of char; ntfs.com define data as an array of const unsigned char.

指针/数组的区别不是问题; const 部分并不重要(但我建议您也将 data 定义为 const );问题(我想)是如果 char 用负值而不是签名的话,是将 char 转换为 uint32_t 的问题>未签名的字符.

The pointer/array difference isn't a problem; the const part ins't important (but I suggest you to define your data as const too); the problem (I suppose) is the conversion to uint32_t of a char, if char is signed with a negative values, instead of a unsigned char.

一个例子:假设您的 data [i] 的值为-1;使用(uint32_t)data [i] ,如果我还记得的话,首先将 data [i] 转换为 int(-1),然后再转换在 uint32_t(-1)中.这样您就会得到4294967295.

An example: suppose that the value of your data[i] is -1; with (uint32_t) data[i], if I remember well, first data[i] is converted in int(-1) and next in uint32_t(-1). So you get 4294967295.

如果您的 data [i] 是一个 unsigned char ,而不是-1,则 data [i] 的值为255;因此,(uint32_t)数据[i] 首先将255转换为 int(255),即255,紧接着 uint32_t(255),即仍为255.

If your data[i] is an unsigned char, instead of -1 data[i] value is 255; so (uint32_t) data[i] first convert 255 to int(255), that is 255, next to uint32_t(255), that remain 255.

简而言之,我的建议是:改变

Briefly, my suggestion is: change

checksum = (checksum << 31) | ((checksum >> 1) + (uint32_t) data[i]);

checksum = (checksum << 31) | ((checksum >> 1) + (uint32_t) (unsigned char) data[i]);

或者简单地

checksum = (checksum << 31) | ((checksum >> 1) + (unsigned char) data[i]);