I misunderstood an assignment, how to write to the professor apologizing and asking for extension?
The first key question that I think you need to consider is the reason why the professor has asked you to do this assignment.  Is it for your educational benefit, or is it so that the professor can evaluate your capabilities as a programmer?  Often, when dealing with students, especially foreign students, a professor will pose assignments as a way of gaining more insight into the students actual as opposed to "on paper" knowledge and skills.  You are also in a situation where even if you have been working hard for the past few weeks, the professor has no way of observing that, and may gain an impression of you as a person who slacks off and makes excuses.

Given these two statements, my recommendation would be to send a short email containing the following three items:


A short statement of your mistake, just as you gave here.
A short polite request for an extension, including an estimate of how many days you will need to finish the assignment correctly.
An attachment of all of the work that you have produced thus far (or link to it, if is is more an ~1MB in size, to avoid possible email bounce problems)


Attaching the work that you have done will allow the professor to make use of it in deciding how to interpret your mistake and request for extension.  Assuming you've been doing solid work, they will be more likely to a) not evaluate you as a slacker and b) actually grant the extension.  Moreover, if the specifics of the assignment was less important than the quality of the work you produce, the professor might even change the assignment to match what you have done.