Namespaces
Variants

std:: as_bytes, std:: as_writable_bytes

From cppreference.net
定義済みヘッダー <span>
template < class T, std:: size_t N >

std:: span < const std:: byte , S /* 詳細は下記参照 */ >

as_bytes ( std:: span < T, N > s ) noexcept ;
(1) (C++20以降)
template < class T, std:: size_t N >

std:: span < std:: byte , S /* 詳細は下記参照 */ >

as_writable_bytes ( std:: span < T, N > s ) noexcept ;
(2) (C++20以降)

span s の要素のオブジェクト表現へのビューを取得します。

N std::dynamic_extent の場合、返されるスパン S のエクステントも std::dynamic_extent となる。それ以外の場合、エクステントは sizeof ( T ) * N となる。

as_writable_bytes は、 std:: is_const_v < T > false の場合にのみ、オーバーロード解決に参加します。

戻り値

1) { reinterpret_cast < const std:: byte * > ( s. data ( ) ) , s. size_bytes ( ) } で構築されたspan。
2) { reinterpret_cast < std:: byte * > ( s. data ( ) ) , s. size_bytes ( ) } で構築されたspan。

#include <cstddef>
#include <iomanip>
#include <iostream>
#include <span>
void print(float const x, std::span<const std::byte> const bytes)
{
    std::cout << std::setprecision(6) << std::setw(8) << x << " = { "
              << std::hex << std::uppercase << std::setfill('0');
    for (auto const b : bytes)
        std::cout << std::setw(2) << std::to_integer<int>(b) << ' ';
    std::cout << std::dec << "}\n";
}
int main()
{
    /* mutable */ float data[1]{3.141592f};
    auto const const_bytes = std::as_bytes(std::span{data});
    print(data[0], const_bytes);
    auto const writable_bytes = std::as_writable_bytes(std::span{data});
    // IEEE 754 浮動小数点規格における符号ビット(最上位ビット)を変更
    writable_bytes[3] |= std::byte{0B1000'0000};
    print(data[0], const_bytes);
}

出力例:

 3.14159 = { D8 0F 49 40 }
-3.14159 = { D8 0F 49 C0 }

関連項目

指定されたストレージ内にオブジェクト表現を再利用して暗黙的にオブジェクトを作成する
(関数テンプレート)
(C++17)
バイト型
(列挙型)