The javadoc for toByteArray tells you
java.lang.IndexOutOfBoundsException - if bytes.length < (bitLength() >> 3) + 1
Thus in should be >= (bitLength() >> 3) + 1
What you have done is nearly the same except you have not added the 1.
So (int)Math.ceil((double)y.bitLength() / 8.0) -1
but easier to use the documented version
y.(bitLength() >> 3) + 1