ByteAccess made easy

OP #6094334
Lesenswert?

Auch schon oft diskutiert wurde der Zugriff auf die einzelnen Bytes 
eines integralen Typs.

Dazu gibt es ja viele (richtige und falsche) Lösungen. Die 
shift-Variante ist in jedem Fall korrekt und constexpr (solange 
std::bit_cast noch nicht verfügbar ist, wohl die einzige als constexpr).

Die Variante mit structured-bindings finde ich ganz nett:
1
volatile const auto r = 0x04030201;
2

3
int main() {
4
    using etl::bytesOf;
5
    const auto [b1] = bytesOf(uint8_t{0x01});
6
    const auto [lsb2, msb2] = bytesOf(uint16_t{0x0201});
7
    const auto [lsb3, b31, b32, msb3] = bytesOf(r);
8
    const auto [lsb4, b41, b42, msb4] = bytesOf(0x04030201);
9
    const auto [lsb5, b51, b52, b53, b54, b55, b56, msb5] = bytesOf(0x0403020104030201UL);
10
        
11
//    const auto x1 = bytesOf(r).get<4>(); // compiletime-error
12

13
    const auto x1 = bytesOf(r).get<3>();
14
    const auto x2 = get<1>(bytesOf(r));
15
            
16
    constexpr auto x3 = get<1>(bytesOf(0x04030201));
17

18
    return (int)msb3;
19
}

Der komplette Code ist in der angehängten Datei.
Angehängte Dateien:

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren