Example #4: bit manipulation

This function implements the block byte swap from Example #3. It byte-swaps the 128-bit block input, and adds an extra bit, to return a 129-bit result. The code is straightforward, and illustrates bitfield and bit-set operations (the last statement sets the top bit of the returned value).

result is a built-in variable, and assigning to it will set the return value from the function (this is a feature which is seen in an identical or similar form in various other languages, such as e, Pascal, and Verilog). The return statement can alternatively be used to return a value. This function returns a bit variable, and result therefore initialises to all zero (129'h0, to be precise).

bit129 byte_swap(bit128 block, int nbytes) {
   int src_lo = 120;
   int dst_lo = 0;

   for(int i=0; i<nbytes; i++) {
      result.(dst_lo+7:dst_lo) = block.(src_lo+7:src_lo);
      src_lo -= 8;
      dst_lo += 8;
   }

   result.(nbytes*8) = 1;     // set the top bit
}