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

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

问题描述

(我已经看过这些问题(将字节转换为整数/C中的uint 将字节数组转换为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.

编辑:通过一些琐碎的技巧,可以(可能)加快速度.如下所示的内容应在低端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天全站免登陆