What is the correct way to write 'niu bi', and how did it get its meaning in Chinese?
niu bi = f**king awesome in English.
And niu in slang means awesome.

The usage is pretty same as in English.

For example:

A：我能一连吃10个汉堡.
   I can eat 10 burgers in a row.
B：牛啊！
   Awesome!

A: 你好牛，这么难得题目你也会做！
   You are so awesome. You can even do such difficult questions!
B: 谢谢。
   Thanks.


Additionally, regarding to 牛X or 牛叉.
It is common in online forums/tweets/blogs, but it is rare in conversations.
Reason is same as people write LOL online very often but seldom say L-O-L in conversations.

If you want to be polite, say 牛 instead of 牛X or 牛叉