Created
July 28, 2021 08:47
-
-
Save Liscare/3834b8ba79b4df14d71616b1b197f96d to your computer and use it in GitHub Desktop.
Hamming 24/18 function in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Hamming function | |
* | |
* @author Liscare | |
* @version 1.0 | |
*/ | |
public class Hamming { | |
/** | |
* Transform 18 bits into 24 bits thanks to Hamming function. | |
* | |
* @param byte1 First byte (max 63) | |
* @param byte2 Second byte (max 31) | |
* @param byte3 Third byte (max 127) | |
* @return Array of 3 bytes encoded by Hamming 24/18 | |
*/ | |
public static byte[] encodeHamming2418(int byte1, int byte2, int byte3) { | |
int d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18; // Data bits | |
int p1, p2, p3, p4, p5, p6; // Protection bits | |
// Get data bits | |
d1 = byte1 & 1; | |
d2 = (byte1 >>> 1) & 1; | |
d3 = (byte1 >>> 2) & 1; | |
d4 = (byte1 >>> 3) & 1; | |
d5 = (byte1 >>> 4) & 1; | |
d6 = (byte1 >>> 5) & 1; | |
d7 = byte2 & 1; | |
d8 = (byte2 >>> 1) & 1; | |
d9 = (byte2 >>> 2) & 1; | |
d10 = (byte2 >>> 3) & 1; | |
d11 = (byte2 >>> 4) & 1; | |
d12 = byte3 & 1; | |
d13 = (byte3 >>> 1) & 1; | |
d14 = (byte3 >>> 2) & 1; | |
d15 = (byte3 >>> 3) & 1; | |
d16 = (byte3 >>> 4) & 1; | |
d17 = (byte3 >>> 5) & 1; | |
d18 = (byte3 >>> 6) & 1; | |
// Create protection bits | |
p1 = (d18 ^ d16 ^ d14 ^ d12 ^ d11 ^ d9 ^ d7 ^ d5 ^ d4 ^ d2 ^ d1) == 1 ? 0 : 1; | |
p2 = (d18 ^ d17 ^ d14 ^ d13 ^ d11 ^ d10 ^ d7 ^ d6 ^ d4 ^ d3 ^ d1) == 1 ? 0 : 1; | |
p3 = (d18 ^ d17 ^ d16 ^ d15 ^ d11 ^ d10 ^ d9 ^ d8 ^ d4 ^ d3 ^ d2) == 1 ? 0 : 1; | |
p4 = (d11 ^ d10 ^ d9 ^ d8 ^ d7 ^ d6 ^ d5) == 1 ? 0 : 1; | |
p5 = (d18 ^ d17 ^ d16 ^ d15 ^ d14 ^ d13 ^ d12) == 1 ? 0 : 1; | |
p6 = d18 ^ d15 ^ d13 ^ d12 ^ d11 ^ d8 ^ d6 ^ d5 ^ d3 ^ d2 ^ d1; | |
// Create 3 bits as a result | |
int resultBit1 = p1 + (p2 * 2) + (d1 * 4) + (p3 * 8) + (d2 * 16) + (d3 * 32) + (d4 * 64) + (p4 * 128); | |
int resultBit2 = d5 + (d6 * 2) + (d7 * 4) + (d8 * 8) + (d9 * 16) + (d10 * 32) + (d11 * 64) + (p5 * 128); | |
int resultBit3 = d12 + (d13 * 2) + (d14 * 4) + (d15 * 8) + (d16 * 16) + (d17 * 32) + (d18 * 64) + (p6 * 128); | |
return new byte[]{(byte) resultBit1, (byte) resultBit2, (byte) resultBit3}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment