Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
13 years ago

Shift operator

Hi,

I have a question regarding the shift operation in the below piece of code :

CODE :

always @(mem_addr)

begin

op_mem_addr = mem_addr;

x = 1 << mem_addr;

end

OUTPUT:

0 op_mem_addr = 1 x = 2# 10 op_mem_addr = 2 x = 4# 20 op_mem_addr = 3 x = 8# 30 op_mem_addr = 4 x = 16# 40 op_mem_addr = 8 x = 0# 50 op_mem_addr = 16 x = 0

1) Isn't The syntax for shift operator : variable << no_of_bits ?? OR can it also be no_of_bits << variable ? Because the above code works!!

2) Left shift is same as doubling the number. Y is the above code working only for some numbers. How can 1 << 3 be equal to 8??

3) All the registers are 8bits.. Y is it that the output is 0 for numbers beyond 8?

Kindly reply if you can understand what is going on here. I dont know what is wrong :(

Thanks.

2 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    I'm a chinese student,so my English is poor. But I will try my best to answer your questions.

    1)

    It should be variable << no_of_bits.

    2)

    Because the value of the variable << no_of_bits is bigger than h00ff when the no_of_bits is bigger than 7.

    3)

    Because the no_of_bits is too big.
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    This shift operation is

    expression_to_be_shifted << expression_number_of_bits_to_shift

    According to Table 11-21 of the LRM, the bit length of a shift operation result is the same as the the length of the expression_to_be_shifted. In your case 1 is implicitly 32'd1, a 32-bit length. However, since x is an 8-bit variable, the left 24 bits of the result are truncated.