Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- // Function to calculate the position of a parity bit (which is 2^r)
- int getParityPosition(int r) {
- return (1 << r); // Equivalent to 2^r (bitwise left shift)
- }
- // Function to calculate and set the parity bits in the Hamming code
- void findParityBits(vector<int>& hammingCode, int totalBits) {
- int r = log2(totalBits + 1); // Number of parity bits
- for (int i = 0; i <= r; i++) {
- int parityPos = getParityPosition(i) - 1; // Convert to 0-indexed position
- int count = 0;
- for (int j = parityPos; j < totalBits; j += (2 * (parityPos + 1))) {
- for (int k = j; k < min(totalBits, j + parityPos + 1); k++) {
- if (hammingCode[k] == 1) {
- count++; // Count the number of 1's for parity calculation
- }
- }
- }
- hammingCode[parityPos] = (count % 2 == 0) ? 0 : 1; // Set parity bit (even parity)
- }
- }
- // Function to generate the Hamming code from the given data bits
- vector<int> generateHammingCode(vector<int>& dataBits) {
- int m = dataBits.size(); // Number of data bits
- int r = 0;
- // Calculate the number of parity bits needed
- while ((1 << r) < (m + r + 1)) {
- r++;
- }
- // Total length of Hamming code
- int totalBits = m + r;
- vector<int> hammingCode(totalBits, 0);
- // Place data bits in the correct positions (skipping parity bit positions)
- for (int i = 0, j = 0; i < totalBits; i++) {
- if (__builtin_popcount(i + 1) != 1) {
- hammingCode[i] = dataBits[j++];
- }
- }
- // Calculate and set parity bits
- findParityBits(hammingCode, totalBits);
- return hammingCode;
- }
- int main() {
- // Example data bits
- vector<int> dataBits = {1, 0, 1, 1}; // Change this as needed
- // Generate the Hamming code
- vector<int> hammingCode = generateHammingCode(dataBits);
- // Print the resulting Hamming code
- cout << "Hamming Code: ";
- for (int bit : hammingCode) {
- cout << bit << " ";
- }
- cout << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement