0

why I am not geting the same result after encoding a string in base64 with JAVA and arduino library

Arduino code:

char data[] = "0123456789012345";
int inputLen = sizeof(data);
char encoded[100];
base64_encode(encoded, data, inputLen);

Serial.print("encoded base 64:");
Serial.println(encoded);

Arduino code result

encoded base 64:MDEyMzQ1Njc4OTAxMjM0NQA=

Java code:

static String message= "0123456789012345";
/////
String encoded = DatatypeConverter.printBase64Binary(message.getBytes());
System.out.println("encoded value is \t" + encoded);

Java code result:

encoded value is    MDEyMzQ1Njc4OTAxMjM0NQ==

Why is the arduino library adding extra data at the end?

Thanks!

1 Answer 1

1

Because strings are null-terminated. Consequently, when you write

char data[] = "0123456789012345";

you allocate a 17-bytes string, with an hex content of

0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x30 0x31 0x32 0x33 0x34 0x35 0x00

The function is adding also the terminal byte in the base64 encoding. If you want to discard it, change your line to

int inputLen = sizeof(data) - 1;
Sign up to request clarification or add additional context in comments.

2 Comments

A better way would be to use strlen. If his data variable would be defined as char data[20] = "0123456789012345";, your solution would encode 19 character instead of 17.
@gre_gor it depends on why you defined data as 20 bytes. If you wanted to actually send 20 bytes, then the only solution is to use inputLen = sizeof(data) (without the -1). Moreover the sizeof information is added at compile time, while the strlen is computed at runtime (so it's slower and bigger). Of course if you have a variable string length you have to use strlen, but since the OP didn't use that function I assume he never has to change it.

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.