Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,821 answers

573 users

How to use bitwise operators to find whether binary representation of a number is palindrome in C

2 Answers

0 votes
#include <stdio.h>
#include <stdbool.h>

#define TOTAL_BITS 8

int is_binary_representation_of_number_palindrome(unsigned int num) {
    int binary_representation_array[TOTAL_BITS] = {0};
    int i = TOTAL_BITS - 1;
    
    while (num != 0) {
        binary_representation_array[i--] = num & 1;
        num = num >> 1;
    }
    
    for (int i = 0; i < TOTAL_BITS; i++) {
        printf("%d", binary_representation_array[i]);
    }
    
    printf("\n");
    
    for (int i = 0, k = TOTAL_BITS - 1; i < k; i++, k--) {
        if (binary_representation_array[i] != binary_representation_array[k]) {
            return false;
        }
    }
 
    return true;
}

int main()
{
    unsigned int num = 153; // 10011001

    if (is_binary_representation_of_number_palindrome(num)) {
        printf("Palindrome\n");
    } else {
        printf("Not Palindrome\n");
    }

    return 0;
}

  
  
  
/*
run:
  
10011001
Palindrome
  
*/

 



answered Dec 20, 2023 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

void toBinary(unsigned int number, char binaryNumber[]) {
    int i = 0;

    while (number != 0) {
        binaryNumber[i] = (number % 2) + '0';
        i++;
        number /= 2;
    }

    _strrev(binaryNumber);
}

int isBinaryRepresentationOfNumberPalindrome(unsigned int number) {
    char binaryNumber[17] = "";

    toBinary(number, binaryNumber);

    char revBinaryNumber[17] = "";
    strcpy(revBinaryNumber, binaryNumber);
    _strrev(revBinaryNumber);

    return strcmp(binaryNumber, revBinaryNumber) == 0;
}

int main()
{
    unsigned int num = 153; // 10011001

    if (isBinaryRepresentationOfNumberPalindrome(num)) {
        printf("Palindrome\n");
    }
    else {
        printf("Not Palindrome\n");
    }

    return 0;
}




/*
run:

Palindrome

*/

 



answered Jan 6, 2024 by avibootz
edited Jan 7, 2024 by avibootz
...