C unsigned int array and bit shifts

If I have an array of short unsigned ints.

Would move the array [k + 1] by 8 bits, put 8 bits in the lower half of the array [k + 1]?

Or do they just go away when they go beyond the allocated space for an element?

+3
source share
5 answers

They are going away. You cannot affect other bits in this way. Try:

#include <stdio.h>

void print_a (short * a)
{
    int i;
    for (i = 0; i < 3; i++)
        printf ("%d:%X\n", i, a[i]);
}

int main ()
{
    short a[3] = {1, -1, 3};
    print_a (a);
    a[1] <<= 8;
    print_a (a);
    return 0;
}

Exit

0: 1
1: FFFFFFFF
2: 3
0: 1
1: FFFFFF00
2: 3
+4
source

They completely delete the data type; they are not transferred to the next element of the array.

If you want this behavior, you need to encode it yourself with something like (shifting the entire array by four bits):

#include <stdio.h>
int main(void) {
    int i;
    unsigned short int a[4] = {0xdead,0x1234,0x5678,0xbeef};

    // Output "before" variables.

    for (i = 0; i < sizeof(a)/sizeof(*a); i++)
        printf ("before %d: 0x%04x\n", i, a[i]);
    printf ("\n");

    // This left-shifts the array by left-shifting the current
    // element and bringing in the top bit of the next element.
    // It is in a loop for all but hte last element.
    // Then it just left-shifts the last element (no more data
    // to shift into that one).

    for (i = 0; i < sizeof(a)/sizeof(*a)-1; i++)
        a[i] = (a[i] << 8) | (a[i+1] >> 8);
    a[i] = (a[i] << 8);

    // Print the "after" variables.

    for (i = 0; i < sizeof(a)/sizeof(*a); i++)
        printf ("after  %d: 0x%04x\n", i, a[i]);

    return 0;
}

:

before 0: 0xdead
before 1: 0x1234
before 2: 0x5678
before 3: 0xbeef

after  0: 0xad12
after  1: 0x3456
after  2: 0x78be
after  3: 0xef00
+3

, C ( ) array[k] << 8 [k] , , [k ]. , [k + 1] .

foo.c:

unsigned short array[5];

void main() {
  array[3] <<= 8;
}

:

movzwl  array+6(%rip), %eax
sall    $8, %eax
movw    %ax, array+6(%rip)

[3] % eax, .

+2

int 8 8 . 8 , , .

, , 8 unsigned int, , 32- 8 int.

unsigned int x = 0x12345678;
// x is 0x12345678

x <<= 8;
// x is 0x34567800
0

, C int , . , "" , , int 16, 32, 64 , 24 .

, , unsigned int 0 UINT_MAX , UINT_MAX 65535 - int 16 .

8 int , , " "

0

Source: https://habr.com/ru/post/1723586/


All Articles