3

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?

2

1 Answer 1

1

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==')
1
  • in your top level code, do you mean for base64.b64decode(msg) to actually be base64.b64decode(aaa)? Dec 19, 2022 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.