将字节数组转换为整数而不循环的方法? [英] Method to convert byte array to integer without looping?

查看:14
本文介绍了将字节数组转换为整数而不循环的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我见过这些问题(Convert Bytes to Int/uint in C将字节数组转换为 Int24) 但它们似乎比我想要做的更复杂,所以我想我会问.)

(I've seen these questions (Convert Bytes to Int / uint in C and Converting Byte Array To Int24) but they seem more complicated than what I am trying to do, so I thought I would ask.)

我正在 Arduino/Wiring 中进行一些 LED 矩阵编程.出于可能与此处无关的原因,我有一个字节数组表示 LED 行的位状态",我用它来缓冲其他操作的结果.要实际设置 LED(我使用的是 Maxim 7219 芯片),我需要从字节数组中导出一个整数.

I'm doing some LED matrix programming in Arduino/Wiring. For reasons probably not relevant here I have a byte array representing a "bit state" of a LED row, which I use to buffer the result of other operations. To actually set the LEDs (I'm using the Maxim 7219 chip), I need to derive an integer from the byte array.

使用 Arduino/Wiring bitWrite 方法,我下面的精简示例例程可以工作,但是我想知道是否有比循环更快的 C 方法.

Using the Arduino/Wiring bitWrite method, my little stripped down example routine below works but I am wondering if there is a C method which would be faster than looping.

 byte dog[8] = {0,0,1,1,1,1,1,0};
 byte cat;

 for (int i = 0; i < 8; i++){
  bitWrite(cat, i, dog[7-i]);
 }

推荐答案

您可以展开循环:

bitWrite(cat, 0, dog[7]);
bitWrite(cat, 1, dog[6]);
bitWrite(cat, 2, dog[5]);
bitWrite(cat, 3, dog[4]);
bitWrite(cat, 4, dog[3]);
bitWrite(cat, 5, dog[2]);
bitWrite(cat, 6, dog[1]);
bitWrite(cat, 7, dog[0]);

或者在没有库函数的情况下设置位(仅当字节保证为 0 或 1 时才有效):

Or set the bits without a library function (only works if the bytes are guaranteed to be either 0 or 1):

cat = (dog[7] << 0) |
      (dog[6] << 1) |
      (dog[5] << 2) |
      (dog[4] << 3) |
      (dog[3] << 4) |
      (dog[2] << 5) |
      (dog[1] << 6) |
      (dog[0] << 7);

但是 C 中没有内置任何东西可以通过单个命令完成此操作,因此它可能不会比这更快.

But there's nothing built into C to do this with a single command so it probably won't get much faster than that.

通过一些小技巧,这可以(可能)加快一点.类似以下的内容应该适用于 little-endian 32 位处理器:

With some bit-twiddling tricks this can be (probably) sped up a little. Something like the following should work on a little-endian 32-bit processor:

uint32_t int_dog = (uint32_t*)dog;
uint32_t t0, t1;

t0 = int_dog[0];   // .......3.......2.......1.......0
t0 |= t0 << 9;     // ......23......12......01.......0
t0 |= t0 << 18;    // ....0123.....012......01.......0
t1 = int_dog[1];   // .......7.......6.......5.......4
t1 |= t1 << 9;     // ......67......56......45.......4
t1 |= t1 << 18;    // ....4567.....456......45.......4
cat = (t0 >> 20) | (t1 >> 24);

这篇关于将字节数组转换为整数而不循环的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆