Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am trying to take a char and convert it to 6 bit binary. Any idea how one can do this in C#. Here is what I have so far.

C#
char c = '1';
int i = Convert.ToInt32(c);
while (i > 40)
    i -= 8;
Console.WriteLine(Convert.ToString(i, 2));
Console.ReadLine();


The result for this is '100001', where it should be '000001'.

Any ideas?
Posted

In your example the ASCII character '1' is 0x31 hex or 11 0001 in binary which is already 6 bits. However the character 'A' is 0x41 hex or 100 0001 in binary, which is 7 bits. How exactly do you expect to convert that to 6 bits without losing its definition?
 
Share this answer
 
Comments
DominicZA 23-Nov-11 16:36pm    
I am trying to create an AIS decoder using this tutorial: http://www.bosunsmate.org/ais/

Maybe you can help me understand it a bit better?
Richard MacCutchan 23-Nov-11 17:04pm    
Sorry but I don't know what an AIS decoder is, and I am not going to be following that link. Maybe you should talk to the author of the tutorial.
Try this:

C#
private string ascii2ais(string p)
        {
            StringBuilder sb = new StringBuilder();

            char[] chars = p.ToCharArray();
            foreach (char c in chars)
            {
                int i = Convert.ToInt32(c);
                i -= 48;
                if (i>40)
                {
                    i -= 8;
                }

                string sixBit = Convert.ToString(i, 2).PadLeft(6, '0');
                sb.Append(sixBit + " ");
            }

            return sb.ToString();

        }


This should do the trick. At least I tried that 14eG is translated to '000001 000100 101101 010111'
 
Share this answer
 
v2
Comments
Michel [mjbohn] 23-Nov-11 17:55pm    
I love bad votes w/o getting a reason :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900