Translate C program to other programming languages

I am trying to translate a C program. The destination language doesn't really matter, I am just trying to understand what every single part of the program is doing.

I cannot find any detail about:

variable=1;
while(variable);

I understand that this is a loop and that is true (I have read similar questions on stack overflow where a code was actually executed) but in this case there is no code related to this while. So I am wondering, is the program "sleeping" - while this while is executing?

Then, another part I don't understand is:

variable=0;
variable=variable^0x800000;

I believe that value should be 24bits but is this really needed in any other programming language that is not low level as C?

Many thanks


while(variable); implements a spin-lock; ie this thread will remain at this statement until variable is 0. I've introduced the term to help you search for a good technique in your new language.

It obviously burns the CPU, but can be quite an efficient way of doing this if only used for a few clock cycles. For it to work well, variable needs to be qualified with volatile .

variable = variable ^ 0x800000; is an XOR operation, actually a single bit toggle in this case. (I would have preferred to see variable ^= 0x800000 in multi-threaded code.) Its exact use is probably explainable from its context. Note that the arguments of the XOR are promoted to int if they are smaller than that. It's doubtful that variable^0x800000 is a 24 bit type unless int is that size on your platform (unlikely but possible).


I am trying to translate a C program.

Don't translate a C program , unless you are writing a compiler (sometimes called a transpiler - or source to source compiler -, if translating to some other programming language different of assembler) which would do such task. And you'll need a lot of work (at least several months for a naive compiler à la TinyCC, and more probably many dozens of years)

Think in C and try to understand its semantics (much more important than its syntax).

while(variable);

that loop has an empty body. It is more readable to make that empty body apparent (semantics remain the same):

 while(variable) {};

Since the body (and the test) of the loop don't change variable (it has no observable side-effect) the loop will run indefinitely as soon as the initial value of variable is non-zero. This will heat your processor.

But you might have declared that variable as volatile and then have something external changing it.

variable=variable^0x800000;

The ^ is a bitwise XOR. You are toggling (replacing 0 with 1 and 1 with 0) a single bit (the 23rd one, IIRC)


To answer your second question: variable=0; variable=variable^0x800000;

This operation is a bitwise operation called XOR. An XOR operation is usually used to toggle bits regardless of it's previous state: 0 ^ 1 = 1 1 ^ 1 = 0

链接地址: http://www.djcxy.com/p/73296.html

上一篇: 前缀字符串文字与前缀连接?

下一篇: 将C程序翻译成其他编程语言