mdoTomofumi Chiba
1/6/2026, 10:52:41 AM

Java: byte 配列の末尾の null バイトを削除するメソッド

Base64 encode & crypt されたデータを複合するときなどに使う。

private static byte[] trimNullBytes(byte[] data) {
    int endIndex = data.length;
    while (endIndex > 0 && data[endIndex - 1] == 0) {
        endIndex--;
    }
    byte[] trimmed = new byte[endIndex];
    System.arraycopy(data, 0, trimmed, 0, endIndex);
    return trimmed;
}
byte[] decoded = java.util.Base64.getDecoder().decode(trimNullBytes(cipher.doFinal(raw)));
TweetBlueskyLike