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==')
Sign up to request clarification or add additional context in comments.

1 Comment

in your top level code, do you mean for base64.b64decode(msg) to actually be base64.b64decode(aaa)?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.