negative integer to binary string



  • hi,
    how can i convert a negative integer to a binary string? is a two's complement required or could i do a hack like this?

    #include <stdio.h>
    #include <stdbool.h>
    #include <string.h>
    #include <math.h>
    
    // int to binary string
    // 123 -> "01111011"
    char *int2bin(int value) {
    	int len = 0;
    	bool is_negative = false;
    
    	if(value < 0) {
    		is_negative = true;
    		len += 1;
    	}
    
    	value = abs(value);
    	len += log2(value);
    	char *str = calloc('\0', len + 1);
    	int index = len;
    
    	while(value) {
    		if(is_negative && index == 0) {
    			break;
    		}
    
    		str[index] = '0' + value % 2;
    		index--;
    		value = value >> 1;
    	}
    
    	if(is_negative) {
    		str[0] = '1'; // for a negative number the MSB is set!
    	}
    
    	return str;
    }
    
    int main(void) {
    	// your code goes here
    
    	char *str = int2bin(-129);
    
    	printf("%s\n", str);
    
    	return 0;
    }
    


  • It depends on your requirements. Either use two's complement or any other coding scheme. Your method is able to represent "negative zeros". This value can be used for special information, as error marker, representing a NaN, and so on.


Log in to reply