Char nach Struct schreiben



  • Hallo,
    ich habe eine Structure mit Bitfeldern

    struct
    {
    	unsigned char bnv_on_off 	:2; // Bits 0..1
    	unsigned char charge_malfunction_indicator_on_off :2; //Bits 2..3
    	unsigned char acknowledge_of_voltage_demand	:2;     //Bits 4..5
    	unsigned char acknowledge_of_current_demand   :2;     //Bits 6..7
    }status_byte1;
    

    Ich möchte nun eine unsigned char variable nach status_byte1 schreiben.
    unsigned char x = 0x73;
    status_byte1 = x;
    oder
    x = status_byte1;
    ergibt die Fehlermeldung "illegal conversion"

    Kann soetwas überhaupt Funktionieren und wenn ja wie?

    Ich möchte die Syntax status_byte1.charge_malfunction_indicator_on_off = x >>2
    vermeiden.

    Gruß
    Johann



  • Kein Problem mit einer union 🙂

    union
    {
       struct
       {
    	unsigned char bnv_on_off 	:2; // Bits 0..1
    	unsigned char charge_malfunction_indicator_on_off :2; //Bits 2..3
    	unsigned char acknowledge_of_voltage_demand	:2;     //Bits 4..5
    	unsigned char acknowledge_of_current_demand   :2;     //Bits 6..7
       } byte_st;
       unsigned char byte;
    }status_byte1;
    
    ...
    
    //komplettes byte beschreiben
    status_byte1.byte = 0x73;
    
    //nur einzelne bits auslesen
    printf("on_off = %d", status_byte1.byte_st.bnv_on_off);
    


  • union
    {
    	struct
    	{
    		unsigned char bnv_on_off 	:2;
    		unsigned char charge_malfunction_indicator_on_off :2;
    		unsigned char acknowledge_of_voltage_demand	:2;
    		unsigned char acknowledge_of_current_demand   :2;
    	}bits;
    	unsigned char byte;
    }status_byte1;
    

    status_byte1.byte = 0xf0;
    status_byte1.bits.bnv_on_off = 1;

    Funktioniert 🙂

    Vielen Dank


Anmelden zum Antworten