module twos_to_offset(twos,shifted); // this module converts a two's complement number to a positive integer // offset around the middle value (ie N/2). So for example, for an // 8-bit number, the offset is 128. parameter NBITS = 8; parameter MEAN = (1<<(NBITS-1)); input [NBITS-1:0] twos; output [NBITS-1:0] shifted; wire sign = twos[NBITS-1]; wire [NBITS-1:0] mag = sign ? {0,~twos[NBITS-2:0]}+1 : {0, twos[NBITS-2:0]}; wire [NBITS-1:0] shifted = sign ? MEAN-mag : MEAN+mag; endmodule module offset_to_twos(shifted,twos); // this module converts a positive integer offset around its middle // value (ie N/2) to a two's complement number, centered around zero. parameter NBITS = 8; parameter MEAN = (1<<(NBITS-1)); input [NBITS-1:0] shifted; output [NBITS-1:0] twos; wire sign = (shifted <= MEAN); wire [NBITS-1:0] twos = sign ? (~(MEAN-shifted))+1 : shifted-MEAN; endmodule