Advertisement
SAURAVKR

Untitled

Sep 10th, 2024
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to calculate the position of a parity bit (which is 2^r)
  5. int getParityPosition(int r) {
  6. return (1 << r); // Equivalent to 2^r (bitwise left shift)
  7. }
  8.  
  9. // Function to calculate and set the parity bits in the Hamming code
  10. void findParityBits(vector<int>& hammingCode, int totalBits) {
  11. int r = log2(totalBits + 1); // Number of parity bits
  12. for (int i = 0; i <= r; i++) {
  13. int parityPos = getParityPosition(i) - 1; // Convert to 0-indexed position
  14. int count = 0;
  15. for (int j = parityPos; j < totalBits; j += (2 * (parityPos + 1))) {
  16. for (int k = j; k < min(totalBits, j + parityPos + 1); k++) {
  17. if (hammingCode[k] == 1) {
  18. count++; // Count the number of 1's for parity calculation
  19. }
  20. }
  21. }
  22. hammingCode[parityPos] = (count % 2 == 0) ? 0 : 1; // Set parity bit (even parity)
  23. }
  24. }
  25.  
  26. // Function to generate the Hamming code from the given data bits
  27. vector<int> generateHammingCode(vector<int>& dataBits) {
  28. int m = dataBits.size(); // Number of data bits
  29. int r = 0;
  30.  
  31. // Calculate the number of parity bits needed
  32. while ((1 << r) < (m + r + 1)) {
  33. r++;
  34. }
  35.  
  36. // Total length of Hamming code
  37. int totalBits = m + r;
  38. vector<int> hammingCode(totalBits, 0);
  39.  
  40. // Place data bits in the correct positions (skipping parity bit positions)
  41. for (int i = 0, j = 0; i < totalBits; i++) {
  42. if (__builtin_popcount(i + 1) != 1) {
  43. hammingCode[i] = dataBits[j++];
  44. }
  45. }
  46.  
  47. // Calculate and set parity bits
  48. findParityBits(hammingCode, totalBits);
  49.  
  50. return hammingCode;
  51. }
  52.  
  53. int main() {
  54. // Example data bits
  55. vector<int> dataBits = {1, 0, 1, 1}; // Change this as needed
  56.  
  57. // Generate the Hamming code
  58. vector<int> hammingCode = generateHammingCode(dataBits);
  59.  
  60. // Print the resulting Hamming code
  61. cout << "Hamming Code: ";
  62. for (int bit : hammingCode) {
  63. cout << bit << " ";
  64. }
  65. cout << endl;
  66.  
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement