Advertisement

conversion to binary

Started by February 28, 2001 08:04 PM
2 comments, last by Emagen 23 years, 11 months ago
Hi - Can someone please explain to me how to convert a char byte, for example "A" into an 8but binary representation. Any code (c++) would be a great help. Thanks
Took me 3 minutes to get into this post, but here's yer answer:

(we'll use 'A' as an example)

The character 'A' is equal to 65 on the ASCII table right? So to do the convertion you'll have to do some divsion, each non-zero remainder equals a 1 and each remainder of zero equals a 0. Remember to do each successive division using only the integer part of the previous resultant and stop dividing after 1/2. See for yourself... Easy as cake!

    65/2 = 32.5 Remainder = 1 Least significant digit32/2 = 16.0 Remainder = 016/2 =  8.0 Remainder = 0 8/2 =  4.0 Remainder = 0 4/2 =  2.0 Remainder = 0 2/2 =  1.0 Remainder = 0 1/2 =  0.5 Remainder = 1 Most significant digit    


So your answer is 1000001... hey this isn't a homework assignment is it?

Edited by - Xorcist on February 28, 2001 9:28:25 PM
Advertisement
Hey thanks I thought it would be harder than that, but it makes sense now. And no, it is not a HW assignment
Or you could just mask the variable with 00000001, assign that to the LSB, shift right one, assign that to the next bit, shift and repeat.

      UCHAR thechar = 'A';char binarystring[9];binarystring[8] = '\0';binarystring[7] = (thechar & 1 ? '1' : '0');for(int i=6, i>=0; i--){  thechar >>= 1;   binarystring[i] = (thechar & 1 ? '1' : '0');}// binarystring should now be "01000001", I think      


Harry.

Edited by - HarryW on February 28, 2001 12:04:14 AM
Harry.

This topic is closed to new replies.

Advertisement