douxi1738 2012-07-10 12:44
浏览 174
已采纳

CRC32从C ++ / C#到PHP

I'm not good at algorithms like CRC32, MD5 etc. so I'm even having difficulty asking the question :)

Basically there is a C# application that uses

[DllImport("Crc32.dll")]
private static extern UInt32 CRC32Calc(UInt32 crc32, byte[] buffer, uint length);

and further down in the code uses it in a method Generate like this

UInt32 crc = CRC32Calc(crcSeed, rawData, (uint)rawData.Length);

while using a certain crcSeed value.

My job is to rework the entire Generate method into a PHP function while preserving the correct CRC calculation.

I think that the PHP's

int crc32 ( string $str )

function will not work because I can't set the crcSeed. So my question is:

how can I make the exact crc32 calculation in PHP without resorting to outside dll's etc. so I can use the code an a Linux machine?

EDIT:

CRC is calculated in chunks with the crcSeed being the initial one.

The CRC32Calc method is actually using the SCTP CRC-32C version, so now, only a PHP implementation is needed.

  • 写回答

1条回答 默认 最新

  • doubailian4459 2012-07-10 13:17
    关注

    In general, data is processed a chunk at a time instead of all at once, in order to have the memory usage of an application constant as opposed to proportional to the length of the input. As a result, you need functions that can process data a chunk at a time. crc functions are written to support this, so they accept the crc value so far from the previous chunks as an argument, and the function then computes the crc value after applying the data in the current chunk.

    updated_crc = crc(last_crc, this_chunk_data_pointer, this_chunk_length)
    

    The crc value so far is what you are calling the "seed".

    The very first crc you provide for the first chunk is the crc value of a zero-length sequence. It is defined by the crc standard in use. Typically it's zero, but it can be other values such as all binary ones.

    first_crc = crc(0, first_chunk_data_pointer, first_chunk_length)
    

    A quick google search does not turn up a built-in function in php that supports computing crc's in chunks -- only all at once. You may need to roll your own. You can find many examples of efficient crc calculations online, which generally use a table of 256 crc's. First you need to know which crc you are calculating based on what it's for. Is it the crc-32 used in gzip, png, ethernet etc.? Is it the crc-32c used in iSCSI? Something else?

    Update:

    Ok, so it's crc-32c. You can look here for a crc code generator that supports that crc (as well as many others).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 爬去app图片链接这是加密了吗 怎么解(语言-java)
  • ¥50 请教Windows server 2012 R2的DCOM配置问题
  • ¥15 adasis v3中LaneConnectivity
  • ¥20 jsp在SpringMVC框架中手动设置域对象失效的场景
  • ¥15 stc -isp烧录时显示通信超时
  • ¥15 VS2022的代码折叠加减号不见了怎么办?
  • ¥15 电脑登录粤政易软件,二维码一直空白,或账号密码登录提示服务器登录失败,是什么原因(相关搜索:防火墙)
  • ¥30 微博热门内容爬虫报错
  • ¥15 selenium获取非固定位置的元素
  • ¥50 手写签名不能上传的问题