使用arduino / c / c ++中的endian操纵对24位字节数组的字节顺序重新排序?

时间:2019-01-21 18:49:09

标签: c++ arduino

我有一个24位数组:

uint32_t rgbdata[] = { 0x00ff00 0xff0000 0x0000ff ...... }

假设上述数据是RGB顺序,而我想要GRB顺序

uint32_t grbdata[] = { 0xff0000 0x00ff00 0x0000ff ...... }

不使用循环,是否有一种快速的字节序处理方式来执行某个字节顺序?在这种情况下,速度至关重要。

1 个答案:

答案 0 :(得分:0)

这是uint24_t的部分示例,您可以移植到您的工具(我不知道arduino的“当前”工具集)

create_task

典型输出:

// Note: compile with -std=c++17 for the using comma list
//       or remove these and put the "std::" into code
#include <algorithm>
using std::swap;

#include <iostream>
using std::cout, std::cerr, std::endl, std::hex, std::dec, std::cin; // c++17

#include <string>
using std::string, std::to_string; // c++17

#include <sstream>
using std::stringstream;


class Uint24_t
{
public:
   Uint24_t() : data {0,0,0}
      {
         cout << "\n  sizeof(Uint24_t)= " << sizeof(Uint24_t) // reports 3 bytes
              << " bytes, * 8= " << (sizeof(Uint24_t) * 8) << " bits." << endl;
      }

   Uint24_t(uint32_t initVal) : data {0,0,0}
      {
         data[0] = static_cast<uint8_t>((initVal >>  0) & 0xff); // lsbyte
         data[1] = static_cast<uint8_t>((initVal >>  8) & 0xff); //
         data[2] = static_cast<uint8_t>((initVal >> 16) & 0xff); // msbyte
         cout << "\n  sizeof(Uint24_t)= " << sizeof(Uint24_t) // reports 3 bytes
              << " bytes, * 8= " << (sizeof(Uint24_t) * 8) << " bits." << endl;
      }

   ~Uint24_t() = default;

   std::string show() {
      stringstream ss;
      ss << "  show(): "
         << static_cast<char>(data[2]) << "."
         << static_cast<char>(data[1]) << "."
         << static_cast<char>(data[0]);
      return ss.str();
   }

   std::string dump() {
      stringstream ss;
      ss << "  dump(): " << hex
         << static_cast<int>(data[2]) << "."
         << static_cast<int>(data[1]) << "."
         << static_cast<int>(data[0]);
      return ss.str();
   }

   void swap0_2() { swap(data[0], data[2]); }


private:
   uint8_t  data[3]; // 3 uint8_t 's
};



class T976_t // ctor and dtor compiler provided defaults
{
public:
   int operator()() { return exec(); } // functor entry

private: // methods

   int exec()
      {
         Uint24_t  u24(('c' << 16) +  // msbyte
                       ('b' <<  8) +
                       ('a' <<  0));

         cout << "\n  sizeof(u24) = " << sizeof(u24) << " bytes"
              << "\n  " << u24.show()
              << "\n  " << u24.dump() << std::endl;

         u24.swap0_2(); // swapping lsByte and msByte

         cout << "\n  sizeof(u24) = " << sizeof(u24) << " bytes"
              << "\n  " << u24.show()
              << "\n  " << u24.dump() << std::endl;

         return 0;
      }



}; // class T976_t


int main(int , char**) { return T976_t()(); } // call functor