Portabel genug?



  • Hallo,

    die folgende Funktion soll die Bitdarstellung einer beliebigen Datenstruktur ausgeben.

    #include <stdio.h>
    #include <stdlib.h>
    #include <limits.h>
    
    char *bit_darstellung(void *eingabe, size_t groesse)
    {
        size_t i,bit_position;
        int j;
        unsigned char temp;
        char *rueck = malloc(CHAR_BIT * groesse + 1);
    
        if(eingabe != NULL && groesse != 0 && rueck != NULL)
    	{
    		rueck[CHAR_BIT * groesse] = '\0';
                	bit_position = 0;
    		for(i = 0; i < groesse; ++i)
    		{
    			temp = *(((unsigned char*)eingabe) + i);
    			for(j = CHAR_BIT - 1 ; j >= 0; --j)
    			{
    				rueck[bit_position++] = temp & (1 << j) 
                                                                ? '1'
                                                                : '0'
                                                                ;
    
    			}
    		}
        }
    	else
    	{
    		free(rueck);
    		rueck = NULL;
        }	
    
        return rueck;
    }
    
    int main()
    {
        int a = 1;
        char *temp = bit_darstellung(&a, sizeof a);
    
        puts(temp);
        free(temp);
    
        return 0;
    }
    

    Wisst ihr, ob das maximal portabel ist (die Ausgabe ist natürlich nicht portabel)? Oder kennt ihr eine einfachere Methode?

    Gruß Tobias


Anmelden zum Antworten