I wrote a function in plpgsql unpack_numeric_bytes, the most important part of the functions is:
FOR i IN 1..v_length LOOP
v_val := v_val + (get_byte(v_bytes, v_byte_index) << v_bit_shift);
v_bit_shift := v_bit_shift + 8;
v_byte_index := v_byte_index + 1;
END LOOP;
It has worked fine until I came across value that it didnt decode correctly.. and it might be too obvious but I am not seeing it.
The call is: select unpack_numeric_bytes(E'g\\363I\\274', array[4], 'f');
From the code v_length is 4 bytes and it tries to decode E'g\\363I\\274'
Which comes up to : {-1136004249}.. I noticed that
2^32 – 1136004249 = 3158963047, and that is the right answer I am looking for ! (tested it with python unpack function).
What is throwing it off? and what am I doing wrong? This is the first time the function failed me.
Thanks!
Found what the problem was:
Fixed this line: