title: PostgreSQL: bit to smallint
body: <p>As far as I was able to understand in PostgreSQL you are not able to convert from hex or bit to smallint or the other way around.</p>
  
  <p>To convert from int2 to bit16 one can do something like this:</p>
  
  <pre><code>select ((((-32768)::int2)::int4)::bit(32)&lt;&lt;16)::bit(16)
      Result: 1000000000000000
  </code></pre>
  
  <p>But how can we do it the other way around?</p>
  
  <p>I have a int2 flag where I want to set the highest bit. But since I can't use my bit operations with int2 I have to convert it to int4 before, so I can do this. Something like this:</p>
  
  <pre><code>SELECT flags, 
         (flags | x'8000'::integer) myInt2Result 
    FROM MyTable;
  </code></pre>
  
  <p>Then I would use myInt2Result to call other processes. 
  To make it more easy to try, lets imagine flags was a smallint with value 2560:</p>
  
  <pre><code>SELECT 2560::int2, (2560::int2 | x'8000'::integer)
      RESULT: 35328        
  </code></pre>
  
  <p>Since this is > than +32767 and I don't have an unsigned smallint in PostgreSQL I cannot cast it directly to int2 (smallint out of range).</p>
  
  <p>Also: in PostgreSQL we cannot do</p>
  
  <pre><code>x'8000'::int2 (it would be really handy) 
  OR
  x'8000'::integer::int2 (smallint out of range) 
  </code></pre>
  
  <p>Is there a way to do this in PostgreSQL or will I have to convert my int4 into a int2 myself (considering the bits)?          </p>