c - 通过数组进行位移

标签 c arrays

假设我们在数组中保存了 8 个字节,例如:

char array[8];

所有这些都设置为零:

for (i = 0; i < 7; i++){
array[i] = 0x00;
}

如何将 1 从第一个 LSBit 移动到最后一个 MSBit,例如

0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x02
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x04
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08
0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x10

......................................................

0x08 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x10 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x20 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x40 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x80 0x00 0x00 0x00 0x00 0x00 0x00 0x00

这是我尝试过的,但结果不是我想要的:

    uint8_t buffer[8];

int index = 0 ;
for ( index = 0; index < 8; index++){
        buffer[index] = 0x00;
    } 
*buffer= 0x01;
for( index = 0 ; index < 64; index++){
        *buffer = *buffer<< 1 ;
}

更新

这是我得到的一个例子:

#include <stdio.h>

int main (){
char buffer[2]={0x01, 0x00};
int i ;
for( i = 0 ; i < 12 ; i++){

  printf("0x %2X    %x \n",buffer[0], buffer[1]);
  *buffer <<= 1;
  }

}

输出是:

0x  1    0
0x  2    0
0x  4    0
0x  8    0
0x 10    0
0x 20    0
0x 40    0
0x FFFFFF80    0
0x  0    0
0x  0    0
0x  0    0
0x  0    0

0xFFFFFF80这个我真的看不懂!

最佳答案

哪个字节是“LS byte”,哪个字节是“MS byte”,可能不是很明显。 8 个字符的数组总是像这样在内存中分配:

LS address               MS address
Byte 0, ...              Byte 7

这适用于所有 CPU。所以你问题中的 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 没有任何意义:你误解了数组在内存中的分配方式。您在示例中展示的是如何将 ms 字节中的位 0 左移到 ls 字节中的位 7。这可能没有任何意义。

但是,如果您尝试将此数组打印为 64 位整数,值 array[0]=1 将为您提供 0000000000000001 在小端机器上,但是 0100000000000000 在大端机器上。但是您的问题中没有任何内容表明您想将数组打印为 64 位值,因此不清楚您实际在问什么。

试试这个:

#include <stdio.h>
#include <stdint.h>


typedef union
{
  uint8_t array[8];
  uint64_t u64;
} my_type;

int main()
{
  my_type t = {0};
  t.array[0] = 0x01;
  // how the array is actually allocated:
  for(int i=0; i<8; i++) // 0100000000000000 on all machines
  {
    printf("%.2X", t.array[i]);
  }
  printf("\n");

  // how the array turns out when printed as a 64 bit int:
  printf("%.16llX\n", t.u64); // 0000000000000001 little endian

  // perhaps what you intended to do, on a little endian machine
  t.u64 <<= 63;
  printf("%.16llX\n", t.u64); // 8000000000000000 little endian

  return 0;
}

关于c - 通过数组进行位移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29795637/

相关文章:

c - 函数中的函数

C 不使用 fscanf 从 txt 读取整数

java - 如何通过排序方法组织字符串

arrays - 如何在指定索引处创建具有特定类型的数组?

javascript - JQuery.makeArray() 从 HTMLOListElement 获取值

c - 读取文件然后将数字存储在数组 C 中

c - dup(file_des) 是否等同于 fcntl(filedes, F_DUPFD, 0)?

c - printf 一个文字数字 (int),同时期望一个更短的数字

c - 在 C 中翻转 PPM 图像

ios - 如何从 uint8_t 数组获取 "remove"数组元素或 ge 范围?