# Sign extend bits

**URL:** <https://discourse.myhdl.org/t/sign-extend-bits/542>\
**Category:** Support\
**Created:** [May 9, 2022, 11:03pm UTC](https://discourse.myhdl.org/t/sign-extend-bits/542 "2022-05-09T23:03:02Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![steveg](https://avatars.discourse-cdn.com/v4/letter/s/ecae2f/32.png) [@steveg](https://discourse.myhdl.org/u/steveg)\
**Post date:** [May 9, 2022, 11:03pm UTC](https://discourse.myhdl.org/t/sign-extend-bits/542/1 "2022-05-09T23:03:02Z")

</div>

Hi All,

I have a 4 bit number that I need to sign extend to say ‘WIDTH’ bits … I have read online some older banter but not sure out of that how to do this or if it is supported easily?

I can of course use an if then to test the bit and stuff ones/zeroes …the verilog version is simple (I suspect VHDL is similarly so)

rt \<= {{WIDTH-4{instr[3]}}, instr[3:0]}; // using bit replication

Steve.

---

<div class="post-metadata">

**Author:** ![josyb](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.myhdl.org/josyb/32/5_2.png) [@josyb](https://discourse.myhdl.org/u/josyb)\
**Post date:** [May 10, 2022, 3:36pm UTC](https://discourse.myhdl.org/t/sign-extend-bits/542/2 "2022-05-10T15:36:35Z")

</div>

Steve,

let’s take WIDTH == 8 (for simplicity)  
let’s assume that you declared `rt = Signal(intbv(0,-128,128))`

- then either you have declared `instr = Signal(intbv(0,-8,8))` and `rt.next = instr` is automatically sign-extended
- or you have declared `instr = Signal(intbv(0)[4:])` you can say `rt.next = instr.signed()` and the sign extension is again automatic.

but if you have declared `rt = Signal(intbv(0)[8:])` things get ugly: `rt.next = concat(instr[3], instr[3], instr[3], instr[3], instr)`

VHDL: `rt <= resize(instr, WIDTH);`

Regards,  
Josy

---

<div class="post-metadata">

**Author:** ![steveg](https://avatars.discourse-cdn.com/v4/letter/s/ecae2f/32.png) [@steveg](https://discourse.myhdl.org/u/steveg)\
**Post date:** [May 10, 2022, 10:11pm UTC](https://discourse.myhdl.org/t/sign-extend-bits/542/3 "2022-05-10T22:11:59Z")

</div>

Thanks Josy,

I fell into the last condition, so I declared rt as Signed(intbv(0, -2\*\*(WIDTH-1), 2\*\*(WIDTH-1))) which made my rt as reg signed which is a great outcome and so used instr.signed() - thanks!

Steve.
