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?