When Merlin Alston, a New York City police officer, decided to take a second job in 2010, he offered his services to a longtime friend and drug dealer, prosecutors charged. Mr. Alston eased into the drug trade, at first driving his friend on trips to the Bronx to sell pounds of cocaine.

But over a four-year period, Mr. Alston assumed a larger role in a world of guns and drugs that was clearly at odds with his police work. He carried his police-issued handgun to deals, tipped off his friend to law enforcement raids and flashed his badge to his fellow officers to get him out of trouble.

On Wednesday, a federal judge in Manhattan sentenced Mr. Alston, 34, to 20 years in federal prison for his role in the drug trade. A jury convicted him in October on several charges, including conspiracy to distribute narcotics. He faced a maximum sentence of life in prison.

“Merlin Alston betrayed his city and his shield,” Joon Kim, the acting United States attorney for the Southern District of New York, said in a statement. “Instead of serving and protecting the citizens of New York City, as he swore an oath to do, Alston served and protected drug dealers.”