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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to create union with struct inside in C++

1 Answer

0 votes
#include <iostream>
#include <bitset>

union Example {
    char arr[4]; // 4 bytes
    struct { short hi, lo; } st; // 4 bytes
    int i; // 4 bytes
} u;

void print_bits(int n) { 
    std::bitset<32> bits(n);
    std::cout << bits << '\n';
}

void print_bits(short s) { 
    std::bitset<16> bits(s);
    std::cout << bits << '\n';
}

void print_bits(char ch) { 
    std::bitset<8> bits(ch);
    std::cout << bits << '\n';
}

int main()
{
    u.i = 0xFF00F00F; 

    print_bits(u.i);

    print_bits(u.st.lo);
    print_bits(u.st.hi);
    
    print_bits(u.arr[3]);
    print_bits(u.arr[2]);
    print_bits(u.arr[1]);
    print_bits(u.arr[0]);
}




/*
run:

11111111000000001111000000001111
1111111100000000
1111000000001111
11111111
00000000
11110000
00001111

*/

 



answered Dec 1, 2022 by avibootz
edited Dec 1, 2022 by avibootz

Related questions

2 answers 189 views
1 answer 195 views
1 answer 223 views
2 answers 236 views
1 answer 137 views
1 answer 171 views
...