swap two variables in verilog using XOR

1.9k views Asked by At

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 ?

2

There are 2 answers

2
Greg On BEST ANSWER

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.

1
Hida On

Just create a new variable to hold the new, rearranged, array. This should not generate any logic, you are just rearranging wires.

reg [263:0] reArrBuffer [0:2];

assign reArrBuffer = 
              '{buffer[0],
                buffer[1],
                {buffer[2][263:148], buffer[2][235:226], buffer[2][137:60], buffer[2][147:138], buffer[2][49:0]}
               }; 

Note: You need ' in front of the first { to create an assignment pattern for an unpacked array. It can be removed if buffer and reArrBuffer is packed.