I know that the prefix depends on the last two characters of the uncompressed key.
Not the last; is it prefixed,i.e. added to the beginning.
In secp256k1, for compression we have the following rule;
- prefix
04
means no compression
- prefix
02
means compression with $y$ coordinate is even
- prefix
03
means compression with $y$ coordinate is odd
How to determine the prefix of a SECP256K1 compressed public key
Take the compressed key;
0x036c409d418f9f35322c7bc0e262da2d01d2d4643121c40682d8dfa54434690d24
then look at the first byte; 03
and this mean there is compression and $y$ coordinate is odd.
Take the uncompressed key;
First decompose the first byte then divide the rest into two 32 bytes, first 32-byte is the $x$-coordinate and the last 32-byte is the $y$-coordinate.
0x04
6c409d418f9f35322c7bc0e262da2d01d2d4643121c40682d8dfa54434690d24
680ca09c51340eaef3f365bfaf42f27e620088884525fa9de07df1685a0411f7
so the prefix is 0x04
I need to store a public key in a variable of maximum 32 bytes.
You can't! You need a little more than 32 bytes, you need at most 33 bytes. The reason for this is;
The secp256k1 curve has the $E: y^2 = x^3+7$ equation over $\mathbb{F}_p$ where it is defined by:
$p = 2^{256}-2^{32}-977 = 115792089237316195423570985008687907853269984665640564039457584007908834671663$
If you place the $x$-coordinate value and solve it over $\mathbb{F}_p$ then you will have at most two solutions. So, one needs to determine at least one bit to resolve this - 2 bits is needed since we have three options.
I know that the prefix depends on the last two characters of the uncompressed key.
Less than that; last bit of the y-coordinate.
Any idea how to get the prefix from the compressed key?
Already answered, however, I read this as how to determine the prefix from uncompressed key. In this case look at the last bit of $y$-coordinate.
How to reduce the size ( comments integration)
The obvious solution is the agreement to always use even $y$ so that when people agreed to use always compression, then we no need to prefix byte to indicate compression and $y$'s selection.
Dave Thompson indicated that Bitcoin Taproot (bip-0340) do this and now every public key has two secret keys.
$$d[G]= (x,y) \text { and } (n-d)[G]= (x,n-y)$$
to see this
$$(n-d)[G] = [n]G - [d][G] = \mathcal{O} - [d]G = - (x,y) = (x, -y)$$
Another one is; for a random ~256 keys, we will have the leading or trailing of the public key will have zero byte. So, one generates random private keys until leading byte is zero ( pre-determined to be leading or trailing ). This only reduces the private key space around one byte. So, for one it we loose one bit, and for one byte we loose one byte.