Runningsnail
Runningsnail

Reputation: 29

Why is "0" "1" sometimes printed as a character and sometimes as ASCII 48/49?

I noticed this when I was writing code.

To xor the elements in the character array, why do some display 0/1 and some display ASCII? How do I get them all to behave like number 0 or 1?

In function XOR, I want to xor the elements in two arrays and store the result in another array.

In main, I do some experiments.

And by the way, besides printing the results, I want to do 0 1 binary operations. Such as encryption and decryption.

Here is a piece of C code.

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

int XOR(char *u, char *w, char *v)
{
    for(int i = 0; i < 16; i++)
    {
        u[i] = w[i] ^ v[i];
    }

    return 0;
}

int PrintList(char *list, int n)
{
    for(int i = 0; i < n; i++)
    {
        printf("%d", list[i]);
    }
    return 0;
}

int main()
{
    char u[17] = "";
    char w[17] = "0001001000110100";
    char v[17] = "0100001100100001";

    XOR(u, w, v);
    PrintList(u, 16);
    printf("\n");

    char w2[17] = "1000110011101111";
    XOR(u, w2, v);
    PrintList(u, 16);
    printf("\n");

    char v2[17] = "1111111011001000";
    XOR(u, w2, v2);
    PrintList(u, 16);
    printf("\n");

    char x[17] = "0101101001011010";
    XOR(u, x, u);
    PrintList(u, 16);
    printf("\n");

    memcpy(w, u, 16);
    XOR(u, w, v);
    PrintList(u, 16);
    printf("\n");

    return 0;
}

The result

0101000100010101
1100111111001110
0111001000100111
48484948494848484849494949494849
0110101101011100

Process returned 0 (0x0)   execution time : 0.152 s
Press any key to continue.

Well, change my declarations from char to unsigned char, maybe due to printf("%d", list[i]);The print results no changes. Change to printf("%c", list[i]);The print results:

0010100001111101

Process returned 0 (0x0)   execution time : 0.041 s
Press any key to continue.

Upvotes: 0

Views: 182

Answers (2)

manuell
manuell

Reputation: 7620

Character '0' is ‭00110000‬ in binary. '1' is 00110001.

'0' ^ '0' = 00000000 (0)
'0' ^ '1' = 00000001 (1)
'1' ^ '1' = 00000000 (0)

But then you reuse the u array.

'0' ^ 0 = 0011000 (48)
'0' ^ 1 = 0011001 (49)
'1' ^ 0 = 0011001 (49)
'1' ^ 1 = 0011000 (48)

Upvotes: 1

Lundin
Lundin

Reputation: 214495

These are strings so you initially have the ASCII codes 48 (0011 0000) and 49 (0011 0001). The ^ operator is bitwise XOR so the result of two operands with the values 48 and 49 can either be 0 or 1. When you print that result as integer, you get 0 or 1 as expected.

If you later use the result of that operation though, you no longer have an array of ASCII codes, but an array of integers with the value 0 or 1. If you XOR that one with an array that is still an ASCII code array, for example 0011 0000 ^ 0, you will get the result 0011 0000, not 0. And so printf gives you 48 etc.

Upvotes: 1

Related Questions