I can - and did at times - program for 36h straight.
I think the worst thing I ever went through was a week with about 10 hours of sleep or so.
For me, caffeine and energy drinks did not help. In fact, on such a long term, caffeine can have rather negative effects. My advice is to drink a lot. Keeps you hydrated and the walks to the toilet are a nice side effect: You stretch your legs a bit and you automatically make short breaks.
That being said, I find this increasingly hard. I would suppose it is a capacity, that is drained and eventually exhausted. And maybe has some negative health effects - physical or mental, long or short term, I can't tell.
What I can tell is that you feel like a zombie and you will continue to feel like that the days after such a marathon. Personally, I had a really big burnout after doing this frequently for about a year.
That is to say: Some people can work efficiently for such a time span, but it comes at a cost.
It was usually the consequence of poor planning and having had no experience in filling the gaps left by non-technical project leads, it was the only option.
Now you will rarely find quality code being produced during such marathons. However the main cause of this are the circumstances, in which those marathons occur: Situations, where you need to deliver features X, Y and Z within a very short time frame. Nobody really cares for code quality at that point, which is why you amass a lot of technical debt through quickfixes and other hacks.
At the same time this indicates the intact performance of the brain: Quickfixes and hacks require both overview and creativity.
You should not forget, that quality code is rarely written in a single run. Especially if the code has a long life span. Code quality is achieved through review and refactoring. Nobody will bother doing that 48h before a deadline.
The bottom line is: You should only work as long as you can and not longer. If you can work only for 4h, then ok. Take a break and work thereafter. Trying to stay awake for 36 hours within which you get 8h of work done is pointless. You get twice the work done if you make 4 sessions of 4h each and use the remaining 20h to regenerate.
If you can work such long hours, it means you are more flexible in responding to underestimation. However the long term solution is improving your planning and estimation process. If that is impossible at your work place, switch jobs. If people expect you to work such long hours, switch jobs. You don't have to prove anything to anyone.