Home > Back-end >  How many bytes are used for signed integer?
How many bytes are used for signed integer?

Time:03-08

This is a code to display the hexadecimal and binary representations of integers and characters.

#include <stdio.h>
#include <string.h>

typedef unsigned char byte;

void show_bytes(byte *bytes , int len)
{
    for(int i=0; i<len; i  ) {
    printf("%-9.2X",bytes[i]);
}
printf("\n");
}

void show_binary(byte *bytes , int len)
{
    for(int i=0; i<len; i  ) 
    {
        byte b = bytes[i];
        for(int j=sizeof(byte)*8-1; j>=0; j--)  
        {
            printf("%c" ,((1<<j)&b)?'1':'0');
        }
        printf(" ");
        }
        printf("\n");
}
void show_int(int x)
{
    printf("Integer: %d\n",x);
    show_bytes ((byte *)&x, sizeof(int));
    show_binary ((byte *)&x, sizeof(int));
}
void show_string(char *x)
{
    printf("String: %s\n", x);
    show_bytes ((byte *)x, strlen(x));
    show_binary ((byte *)x, strlen(x));
}

int main()
{
    show_int (-5);
    show_string("abcd");
}

And the results of this code is as follow Code Result The question is how to read the result for both the interger and character, from my understanding the binary representation of -5 is

11111011 11111111 11111111 11111111

while for character 'a' is

01100001

is it right? And is it stored in signed magnitude, one’s complement, or two’s complement?

CodePudding user response:

How many bytes are used for signed integer?

printf("%zu\n", sizeof(int));  // Often 4

CodePudding user response:

Based on your program output, it appears that your platform has 32-bit integers and is little-endian. So, being little-endian, the sequence FB FF FF FF means that the actual value of the int is FFFFFFFB, which is -5 in 32-bit 2's complement.

  • Related