Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #109 Number of bytes of a type

Set n to the number of bytes of a variable t (of type T).

<T> int bytes(T t) {
    String s = t.getClass().getSimpleName();
    return switch (s) {
        case "Boolean" -> 1;
        case "Byte" -> Byte.BYTES;
        case "Short" -> Short.BYTES;
        case "Character" -> Character.BYTES;
        case "Integer" -> Integer.BYTES;
        case "Float" -> Float.BYTES;
        case "Long" -> Long.BYTES;
        case "Double" -> Double.BYTES;
        default -> -1;
    };
}

This will `box` a primitive data-type argument.
N : Integer := (T'Size + 7) / 8;

T'Size returns size of T in bits. It is the minimum number of bits required to store an object of that type.
Divide by 8 to convert to bytes

New implementation...
< >
programming-idioms.org