DEV Community

ibenge Uforo
ibenge Uforo

Posted on • Updated on

Entry-2: ByteArray conversion (React-native)

Tasked with building a chat client with the telegram API (Post coming soon), I encountered this issue wherein the byte array had to be converted to a base64 string to display a thumbnail.

After a couple of hours of research with no solution in sight of which I did not need aspirin for, the following solution below settled it.

byte[] bytes = new byte[byteArray.size()];

for(inti = 0; i<byteArray.size(); i++){
    /*
     * In this context the values of the array is parsed as a string hence the method 'getString'.
     */
    bytes[i] = Byte.parseByte(byteArray.getString(i));
}
Enter fullscreen mode Exit fullscreen mode

Example with a Base64Converter

public class FileToBase64 {

    public static String convertToBase64 (byte[] imageBytes){

        return Base64.encodeBase64String(imageBytes);

    }

}
Enter fullscreen mode Exit fullscreen mode

Full code

@ReactMethod
public void convertToBase64(Readable ArraybyteArray,Callback callback){
byte[] bytes =new byte[byteArray.size()];

for(inti = 0; i<byteArray.size(); i++){
        bytes[i] = Byte.parseByte(byteArray.getString(i));
    }

// Regular callback gotten from react native
// see - https://reactnative.dev/docs/native-modules-android#callbacks
    callback.invoke( FileToBase64.convertToBase64(bytes));

}
Enter fullscreen mode Exit fullscreen mode

TLDR

  1. Send the byte to the native OS
  2. Convert and return to react-native.

PS: Do comment below if further explanation is required, I am happy to oblige!.

Cheers (:

External links

Latest comments (0)