Check out these two Python methods taken from here
class PublicKey
@classmethod
def decode(cls, key: bytes) -> 'PublicKey':
if key.startswith(b'\x04'): # uncompressed key
assert len(key) == 65, 'An uncompressed public key must be 65 bytes long'
x, y = bytes_to_int(key[1:33]), bytes_to_int(key[33:])
else: # compressed key
assert len(key) == 33, 'A compressed public key must be 33 bytes long'
x = bytes_to_int(key[1:])
root = modsqrt(CURVE.f(x), P)
if key.startswith(b'\x03'): # odd root
y = root if root % 2 == 1 else -root % P
elif key.startswith(b'\x02'): # even root
y = root if root % 2 == 0 else -root % P
else:
assert False, 'Wrong key format'
return cls(Point(x, y))
def encode(self, compressed=False) -> bytes:
if compressed:
if self.y & 1: # odd root
return b'\x03' + int_to_bytes(self.x).rjust(32, b'\x00')
else: # even root
return b'\x02' + int_to_bytes(self.x).rjust(32, b'\x00')
return b'\x04' + int_to_bytes(self.x).rjust(32, b'\x00') + int_to_bytes(self.y).rjust(32, b'\x00')