Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRC32 Java Update 1st Bit

I am trying to create a CRC32 of a string in java. I was able to do that with java.util.zip.CRC32. Now I want to update 1st bit of the crc to 0 or 1 based on some conditions. Can anyone tell me how to do this?

like image 800
Navrattan Yadav Avatar asked Apr 29 '26 08:04

Navrattan Yadav


2 Answers

This should help for the highest bit (it is not clear which one is the first one):

long crc = crc32.getValue();

crc &= 0x7FFFFFFF; //sets the highest bit to 0
if (yourCondition) {
    crc |= 0x80000000; //sets the highest bit to 1
}
like image 58
vojta Avatar answered May 02 '26 00:05

vojta


You can use bitmasking to clear bit 1 first and the add in the bit you want.

CRC32 crc = ...;
boolean condition = ...;
int crc32 = (int) crc.getValue();
int bit = condition ? 1 : 0;
crc32 = (crc32 & ~1) | bit;
like image 30
Erwin Bolwidt Avatar answered May 01 '26 23:05

Erwin Bolwidt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!