How is the P2SH address obtained in decodescript Im trying to understand how to obtain the p2SH address when decoding an output script.

r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));


source

As far as I understand CScriptID is the hash160 of the script.
So, a P2SH scriptPubKey looks like this:

OP_HASH160 &lt;20 byte script hash&gt; OP_EQUAL


Serialized, in hex, that looks like:

17a9140000000000000000000000000000000000000087

^ ScriptPubkey len 
  ^ OP_HASH160
    ^ Data element len
      ^ Data element
                                            ^ OP_EQUAL


where the zeros can be any byte.

How does that transform into an address starting with 3? You transform it the same way you would a normal Bitcoin address, but with a different version byte. Instead of 00, you would use 05. 

See also the P2SH address specification.