Ask how to convert the java code of crc16 to php

Source: Internet
Author: User
Could you tell me how to convert the java code of crc16 to the php Post? Finally, the Post is edited by oelenson from 2014-06-211:49:27? this & nbsp; crc & nbsp; 16 & nbsp; how to convert the java code of to php, and use php & nbsp; the code to be converted is incorrect $ str2AQEBAQEB; $ str2 how can I convert the java code of crc 16 to php?

This post was last edited by oelenson at 12:49:27

How can I convert the java code of crc 16 to php?

$ Str2 = 'aqebaqeb ';
$ Str2 = base64_decode ($ str2 );


Java code

public static int CRC16(final byte[] buffer) {
int crc = 0xffff;

for (int i = 0; i < buffer.length; i++) {
crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
crc ^= (buffer[i] & 0xff);
crc ^= ((crc & 0xff) >> 4);
crc ^= (crc << 12) & 0xffff;
crc ^= ((crc & 0xff) << 5) & 0xffff;
}
crc &= 0xffff;

return crc;
}

function uRShift($a, $b)
{
if($b == 0) return $a;
return ($a >> $b) & ~(1<<(8*PHP_INT_SIZE-1)>>($b-1));
}



function crc16($buffer) {
$crc = 0xffff;
for ($i = 0; $i < strlen($buffer); $i++) {
$crc = ((uRShift($crc,8)) | ($crc << 8)) & 0xffff;
$crc ^= ($buffer[$i] & 0xff);
$crc ^= (($crc & 0xff) >> 4);
$crc ^= ($crc << 12) & 0xffff;
$crc ^= (($crc & 0xff) << 5) & 0xffff;
}
$crc &= 0xffff;

return $crc;
}

------ Solution --------------------
Java >>> (0 shifted to the left) does not require special processing in php, you can directly>
At most (crc> 8) is translated into ($ crc> 8) & 0xff)

Java byte [] type, no corresponding php data type
You can get the internal code ord byte ($ buffer [$ I])
You can also enter the function $ buffer = array_values (unpack ('C', $ buffer ));
The array returned by unpack ('C', $ buffer) starts with subscript 1, so sort out array_values.
If you use a foreach loop or a for loop starts from 1, you do not need to sort it out.

Nothing else.

If you think there are still problems, please give several results of java running

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.