When Sonic has rings and bumps into an enemy or other hazard, such as spikes or a field of lava, he's flung backwards. During this special rebounding state, his physics behave quite differently.
His Y speed is set to -4 at the moment of impact, and his X speed is set to 2 times a, where a is the sign of Sonic's X position minus the hazard in question's X position. If a would be 0, it defaults to 1 so that Sonic can never be flung straight upward. The direction Sonic's sprite is facing, however, does not change.
Note: The above is true even for lava fields and rows of spikes. The direction Sonic is flung is always based on which side of the centre of the hazard he's on.
Even if the harmful object is above Sonic, his Y speed is set to -4. If the object is solid, like spikes, he'll detect the collision in the next step and Y speed will be set to 0. This results in Sonic appearing to just fall away from the hazard.
While in the rebounding state, he takes no player input. Also, gravity is changed from 0.21875 (the normal value) to 0.1875 until he lands (perhaps they thought this reduced gravity gave the player more time to react). When he does land, his X speed is set to 0, so that he stops dead. Also, he enters into an invulnerability state which lasts for 120 frames (0x78).
He cannot leave the rebounding state until he hits the ground. In your engine, you may wish to change this, adding a timer that returns him to a normal falling state when it runs out. This is more fair, because without this fix Sonic can be knocked off of a high ledge, and the player is unable to regain control for quite some distance.
In the Sonic 2 Nick Arcade prototype, if Sonic hits a wall at his top X speed of 6, he will bounce away with the identical physics as if he was hit by a harmful object - altered gravity and all. The only differences are that he doesn't lose his rings, and when he lands he spends a few steps in his knocked flat animation.
Granted, this isn't a feature in the finished Sonic 2, or even the later builds of the game, but the effect has been included in the some of the 3D Sonic games.
To tell the truth, reaching a speed of 6 in Sonic 2 is easy enough to do that Sonic seems to be rebounding off of walls all too often, and it gets a little annoying. If you increased the criterion speed to 12, it might be a nice effect to leave in your engine.
When Sonic is killed by a harmful object, his X speed is set to 0, and his Y speed to -7. Gravity remains normal. Of course, Sonic takes no input at this point, either. While in his dying state, he detects no collisions with objects or water surfaces.