Search code examples
verilogfpgaxorhdl

swap two variables in verilog using XOR


I have a line of data of 264 bits in memory buffer written using Verilog HDL.

buffer[2]=264'b000100000100001000000000001000000000000001000001000000000000000000000000000000000000100000010000010000100000000000100000000010000100001100000000000000000000000000000000000010000001000001000010000000000010000000000000010001010000000000000000000000000000000000001000;

I want to transfer 10 bits within the above raw from buffer[2][147:138] bits to buffer[2][59:50], then transfer buffer[2][235:226] bits into buffer[2][147:138]

I try to do this using XOR but it dose not work

buffer[2][59:50]=buffer[2][59:50]^buffer[2][147:138];
buffer[2][147:138]=buffer[2][59:50]^buffer[2][147:138];
buffer[2][59:50]=buffer[2][59:50]^buffer[2][147:138];

buffer[2][235:226]=buffer[2][235:226]^buffer[2][147:138];
buffer[2][147:138]=buffer[2][235:226]^buffer[2][147:138];
buffer[2][235:226]=buffer[2][235:226]^buffer[2][147:138];

How can I do this without using non-blocking assignment ?


Solution

  • You can swap with concatenations, no xor required:

    {buffer[2][147:138],buffer[2][59:50]} = {buffer[2][59:50],buffer[2][147:138]};
    
    {buffer[2][235:226],buffer[2][147:138] = {buffer[2][147:138],buffer[2][235:226]};
    

    Your title says swap, but your description says transfer. To transfer you can can still use the same approach:

    {buffer[2][147:138],buffer[2][59:50]} = {buffer[2][235:226],buffer[2][147:138]}
    
    // Or you can do this, beware order matters
    buffer[2][59:50] = buffer[2][147:138];
    buffer[2][147:138] = buffer[2][235:226];
    

    Be careful where you do this in an always block. It can create a combinational feedback loop after synthesized if done incorrectly. The bits must first be assigned by a determinate value (ideally a flop) before doing the swap.