String to memeoryBlock

Hi there,

Maybe this is a stupid question... but how can I convert a String to memeryBlock? my goal is to use the base64 encoding.

Thanks!

MemoryBlock::fromBase64Encoding ?

Ok, but I need to create first the memory block with the string, and there I have my problem :(

String myString("This is my string");

MemoryBlock mb(myString.toUTF8(), myString.length());


Create the string, then use it's toUTF8() method and cast it to a void * pointer in a memory block
 

Is that getNumBytesAsUTF8( ) is not safer in case of UTF8 characters?

String myText(CharPointer_UTF8("P\xc3\xa9p\xc3\xa9 p\xc3\xa8te en ao\xc3\xbbt!"));

MemoryBlock myBlock(myText.toRawUTF8( ), myText.getNumBytesAsUTF8( ) + 1); 

Thanks!

fwiw this is passing all my units tests, based a bunch on @jules’ responses here.

class FileWritingFunctions
{
public:
    static inline void writeStringToFile (String stringToWrite,
                                          File fileToWriteTo)
    {
        if (! fileToWriteTo.existsAsFile())
            fileToWriteTo.create();

        fileToWriteTo.replaceWithText (stringToWrite);
    }

    static inline String loadStringFromFile (const juce::File& fileToRead)
    {
        if (! fileToRead.existsAsFile()) // [1]
            return "";

        auto fileText = fileToRead.loadFileAsString();

        return fileText;
    }

    static inline MemoryBlock encodeString (BlowFish& blowfish, StringRef text)
    {
        MemoryBlock mb;

        {
            MemoryOutputStream out (mb, false);
            out << text;
        }

        blowfish.encrypt (mb);
        return mb;
    }

    static inline String decodeString (BlowFish& blowfish, MemoryBlock mb)
    {
        blowfish.decrypt (mb);
        return mb.toString();
    }

    static inline void writeStringToFileEncrypted(BlowFish& blowFish, String inputString, File file)
    {
        auto encryptedString = EncryptedFileWritingFunctions::encodeString (blowFish, inputString);
        EncryptedFileWritingFunctions::writeStringToFile (encryptedString.toBase64Encoding(), file);
    }

    static inline String readStringFromEncryptedFile(BlowFish& blowFish, File file)
    {
        auto readString = EncryptedFileWritingFunctions::loadStringFromFile (file);
        MemoryBlock mb;
        mb.fromBase64Encoding (readString);
        auto decodedString = EncryptedFileWritingFunctions::decodeString (blowFish, mb);
        return decodedString;
    }
};
1 Like