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.

40,024 questions

51,976 answers

573 users

How to parse and int bits into an array in C

1 Answer

0 votes
#include <stdio.h>

#define SIZE 16

void int_to_binary_array(unsigned int n, int total, int* bits) {
    unsigned int mask = 1U << (total - 1); // 32768
    
    for (int i = 0; i < total; i++) {
        bits[i] = (n & mask) ? 1 : 0;
        n <<= 1;
    }
}

int main()
{
    int bits[SIZE] = { 0 };

    int_to_binary_array(511, SIZE, bits);

    for (int i = 0; i < SIZE; i++) {
        printf("%d ", bits[i]);
    }

    return 0;
}



/*
run:

0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1

*/

 



answered Jun 28, 2024 by avibootz

Related questions

1 answer 226 views
1 answer 101 views
101 views asked Apr 2, 2024 by avibootz
1 answer 145 views
145 views asked May 5, 2017 by avibootz
1 answer 172 views
172 views asked Feb 16, 2021 by avibootz
...