Skip to content
Advertisement

Conversion Between Base 64 String and Byte Array Varies in C# and Python

I have a C# byte array b_a that has 16 byte length. When I convert b_a to base 64 string aaa, it’s length returns 24

string aaa = Convert.ToBase64String(b_a);
Console.WriteLine(aaa.Length); //24
Console.WriteLine(aaa); //'xKKkTjcKsfBDqpIJBKn6QQ=='

I want to convert aaa string to byte array in Python. But When I convert it, it’s length still returns 24.

aaa = 'xKKkTjcKsfBDqpIJBKn6QQ==' 
b_a = bytearray(aaa)
len(b_a) #24

I want to get initial b_a with all. What is the point that I miss?

Advertisement

Answer

If you have base 64 encoded information, you need to decode it to get bytes. In Python 3 (and in Python 2):

import base64

aaa = 'xKKkTjcKsfBDqpIJBKn6QQ=='
b_a = base64.b64decode(aaa)
len(b_a)  # 16

Given that your code apparently works without an error, you must be using Python 2. Using bytearray on a str object in Python 3 would raise an exception because it doesn’t know how to translate a string to bytes without a string encoding information. But in Python 2, str objects are really sequences of bytes under the hood. So bytearray just returns the str as bytes in Python 2:

>>> aaa = 'xKKkTjcKsfBDqpIJBKn6QQ=='
>>> bytearray(aaa)
bytearray(b'xKKkTjcKsfBDqpIJBKn6QQ==')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement