Luchnik
Luchnik

Reputation: 1087

Bit representation of characters C++

Here's my program for bit representation of characters. But I don't know does it show me right or wrong representation? There are suspicious units (red colored).

enter image description here

Can you explain me what's this (if it's right) or what's wrong with my code if these units should not be. Thanks

#include "stdafx.h"
#include "iostream"
using namespace std;

struct byte {
   unsigned int a:1;
   unsigned int b:1;
   unsigned int c:1;
   unsigned int d:1;
   unsigned int e:1;
   unsigned int f:1;
   unsigned int g:1;                   
   unsigned int h:1;
};

union SYMBOL {                              
    char letter;                    
    struct byte bitfields;
};

int main() {                                                              
    union SYMBOL ch; 
    cout << "Enter your char: ";
    while(true) { 

        ch.letter = getchar();
        if(ch.letter == '\n')  break; 

        cout << "You typed: " << ch.letter << endl;
        cout << "Bite form = ";
        cout << ch.bitfields.h;
        cout << ch.bitfields.g;
        cout << ch.bitfields.f;
        cout << ch.bitfields.e;
        cout << ch.bitfields.d;
        cout << ch.bitfields.c;
        cout << ch.bitfields.b;
        cout << ch.bitfields.a;
        cout << endl << endl;

    }
}

Upvotes: 1

Views: 1197

Answers (2)

gnasher729
gnasher729

Reputation: 52538

Bit fields are not portable. The biggest problem is that you don't know in which order the bits will be assigned to the individual bit fields, but you don't even know actually whether the struct will have 1, 2 or any other number of bytes.

I'd recommend using unsigned char (because you don't know whether char is signed or unsigned), and using code like (ch & 0x80) != 0, (ch & 0x40) != 0 etc.

Upvotes: 3

Maroun
Maroun

Reputation: 95968

See the ASCII table to understand the output you're getting:

enter image description here

  • a has the decimal value of 97, and 97 is 01100001 in binary
  • b has the decimal value of 98, and 97 is 01100010 in binary

and so on.

Upvotes: 5

Related Questions