Go Down

Topic: Bin Dec Hex Oct Converter (Read 4582 times)previous topic - next topic

kopite

Dec 14, 2012, 10:53 am
Hi,

Below is a quick and simple program that should convert a decimal value into binary. At the moment it converts any value to Bin.

A few questions...

1) How can I ensure that the user input in the serial monitor is a decimal value?

2) If I wanted to convert from Hex to Bin, how would i do this and again, how would I ensure that the user input was Hex?

Many Thanks

Code: [Select]
`int val;void setup() { //Initialize serial and wait for port to open:  Serial.begin(9600);    // prints text and menu options for user to select from}  void loop() {   if (Serial.available())  //Constantly checks to see if anything has been sent over the USB Connection and if it needs to be processed   {     val = Serial.read(); //Reads a single letter     //Serial.println(val);     Serial.print(val, BIN);    }}`

AWOL

#1
Dec 14, 2012, 11:11 amLast Edit: Dec 14, 2012, 11:17 am by AWOL Reason: 1
Quote
1) How can I ensure that the user input in the serial monitor is a decimal value?

By rejecting characters other than '0' to '9' inclusive.

Quote
2) If I wanted to convert from Hex to Bin, how would i do this and again, how would I ensure that the user input was Hex?

By rejecting characters other than '0' to '9' inclusive or 'a' to 'f' or 'A' to 'F'

Ultimately, everything is binary.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Nick Gammon

#2
Dec 14, 2012, 11:50 am

1) How can I ensure that the user input in the serial monitor is a decimal value?

See: isdigit function.

2) If I wanted to convert from Hex to Bin, how would i do this and again, how would I ensure that the user input was Hex?

See: isxdigit function.
Please post technical questions on the forum, not by personal message. Thanks!

http://www.gammon.com.au/electronics

kopite

#3
Dec 14, 2012, 12:05 pm
Many thanks for both I your replies.

As I'm a beginner I have never herd of isdigit function etc. I will do some digging on this.

kopite

#4
Dec 15, 2012, 12:32 pm
Hi,

Below is the code for my program, it takes the user input when making a choice from the menu and then takes the user to convert between the specified types.

A couple of questions. Ive used the parseInt for the dec to other ypes but how can i make sure the result for example in binary is 8-bit. This is because i need the user to be able to put in a number between -255 and 255. The minus returns the binary in 32-bit, I need it to be 8-bit.

Also, is there any calculations (or anyway in fact-without using a similar thing to isxdigit) that can ensure the user input is eith HEX, OCT or binary?

Many thanks once again.

Code: [Select]
`void setup() { //Initialize serial and wait for port to open:  Serial.begin(9600);    // prints text and menu options for user to select from   Serial.println(F("Welcome to my Bin, Dec, Oct, Hex Converter"));  delay(500);  Serial.println(F(" "));  Serial.println(F("Please select a number from the options available..."));  Serial.println(F("*Please Note* The options below are Case Sensitive!"));  Serial.println(F(" "));  Serial.println(F("Main Menu"));  Serial.println(F("---------"));   Serial.println(F("a) 2's comp Binary to Hex,"));  Serial.println(F("b) 2's comp Binary to Octal,"));  Serial.println(F("c) 2's comp Binary to Decimal,"));  Serial.println(F("d) Octal to 2's comp Binary,"));  Serial.println(F("e) Octal to Hex,"));  Serial.println(F("f) Octal to Decimal,"));  Serial.println(F("g) Hex to 2's comp Binary,"));  Serial.println(F("h) Hex to Octal,"));  Serial.println(F("i) Hex to Decimal,"));  Serial.println(F("j) Decimal to 2's comp Binary,"));  Serial.println(F("k) Decimal to Hex,"));  Serial.println(F("l) Decimal to Octal."));}void loop() {   int menuselect;   int conversion1;   int conversion2;   int conversion3;   int conversion4;   int conversion5;   int conversion6;   int conversion7;   int conversion8;   int conversion9;   int conversion10;   int conversion11;   int conversion12;         if (Serial.available())  //Constantly checks to see if anything has been sent over the USB Connection and if it needs to be processed    {      menuselect = Serial.read();      switch (menuselect) {  case 97:   //option a) ASCII "a"    Serial.println(F(" "));    Serial.println(F("2's comp Binary to Hex"));       while (Serial.available ()== 0){}       conversion1 = Serial.read();       Serial.println(conversion1, HEX);                 break;  case 98:      Serial.println(F(" "));      Serial.println(F("2's comp Binary to Octal"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       Serial.println(conversion2, OCT);           break;  case 99:       Serial.println(F(" "));     Serial.println(F("2's comp Binary to Decimal"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       conversion2 = conversion2 - '0';       Serial.println(conversion2, DEC);           break;  case 100:       Serial.println(F(" "));     Serial.println(F("Octal to 2's comp Binary"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       Serial.println(conversion2, BIN);           break;  case 101:       Serial.println(F(" "));    Serial.println(F("Octal to Hex"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       Serial.println(conversion2, HEX);           break;  case 102:     Serial.println(F(" "));     Serial.println(F("Octal to Decimal"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       Serial.println(conversion2, DEC);           break;  case 103:       Serial.println(F(" "));     Serial.println(F("Hex to 2's comp Binary"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       Serial.println(conversion2, BIN);           break;  case 104:     Serial.println(F(" "));     Serial.println(F("Hex to Octal"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       Serial.println(conversion2, OCT);           break;  case 105:       Serial.println(F(" "));    Serial.println(F("Hex to Decimal"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       Serial.println(conversion2, DEC);           break;  case 106:       Serial.println(F(" "));     Serial.println(F("Decimal to 2's comp Binary"));    while (Serial.available ()== 0){}       conversion2 = Serial.parseInt();       Serial.println(conversion2, BIN);           break;  case 107:     Serial.println(F(" "));      Serial.println(F("Decimal to Hex"));    while (Serial.available ()== 0){}       conversion2= Serial.parseInt();       Serial.println(conversion2, HEX);           break;  case 108:      Serial.println(F(" "));      Serial.println(F("Decimal to Octal"));    while (Serial.available ()== 0){}       conversion2= Serial.parseInt();       //if using serial.read i could of used conversion2 = conversion2 - '0'       Serial.println(conversion2, OCT);           break;  } }}           `

Nick Gammon

#5
Dec 15, 2012, 09:24 pm

Code: [Select]
`  case 97:   //option a) ASCII "a"`

Why not:

Code: [Select]
`  case 'a':`

Easier to read, don't you think? Ditto for the others.

The rest of the code looks incredibly repetitive. You should be able to collect their input into a buffer in one place and then process it afterwards. For ideas see:

http://www.gammon.com.au/serial

Quote
This is because i need the user to be able to put in a number between -255 and 255. The minus returns the binary in 32-bit, I need it to be 8-bit.

You cannot fit -255 to +255 into 8 bits, if that is what you are saying. You can only fit -128 to +127.
Please post technical questions on the forum, not by personal message. Thanks!

http://www.gammon.com.au/electronics

kopite

#6
Dec 15, 2012, 10:41 pm
Quote
Easier to read, don't you think? Ditto for the others.

That seems so obvious now, lol.

Quote

The rest of the code looks incredibly repetitive. You should be able to collect their input into a buffer in one place and then process it afterwards.

Completely agree but at the moment i'm more concerned that my conversions dont work except the last three. This needs to be completed by Friday, so if you can help me in anyway with the conversions that would be great. I plan on doing the "buffer" thing last.

Many thanks.

PaulS

#7
Dec 15, 2012, 10:51 pm
Quote
Completely agree but at the moment i'm more concerned that my conversions dont work except the last three.

What are you inputting? What is being output? You don't expect us to guess, do you?

Quote
I plan on doing the "buffer" thing last.

I suspect that a change in plans is in your immediate future.

Nick Gammon

#8
Dec 15, 2012, 11:44 pm

Code: [Select]
` case 100:      Serial.println(F(" "));    Serial.println(F("Octal to 2's comp Binary"));    while (Serial.available ()== 0){}       conversion2= Serial.read();       Serial.println(conversion2, BIN);          break;`

If I read the code correctly you are assuming one or two digit input. What if someone enters 0004?

You are best off:

• Collect the input into a buffer, delimited by something (eg. newline)

• Do a conversion on that buffer

My link above shows exactly how to do that for decimal numbers, so it shouldn't take weeks to do.
Please post technical questions on the forum, not by personal message. Thanks!

http://www.gammon.com.au/electronics

kopite

#9
Dec 16, 2012, 12:20 am
Quote
What are you inputting? What is being output? You don't expect us to guess, do you?

Im trying to take input from the serial monitor and convert it between the four formats of Hex, Bin, Dec, Oct. The user makes the choice of what conversion fromat they want to use by choosing from the menu.

I have come across mathematical type conversions in the past but cant find anymore. Like if using the serial.read, as you'll know serial input is ascii so to read it as decimal val = val - '0'. I was wondering if you could do this simple code for all formats after the serial.read function.

Code: [Select]
`void setup() { //Initialize serial and wait for port to open:  Serial.begin(9600); }void loop() { int menuselect; int conversion1; int conversion2; int conversion3; int conversion4; int conversion5; int conversion6; int conversion7; int conversion8; int conversion9; int conversion10; int conversion11; int conversion12;        { // prints text and menu options for user to select from     Serial.println(F(" "));     Serial.println(F("Welcome to my Bin, Dec, Oct, Hex Converter"));     delay(500);     Serial.println(F(" "));     Serial.println(F("Please select a number from the options available..."));     Serial.println(F("*Please Note* The options below are Case Sensitive!"));     Serial.println(F(" "));     Serial.println(F("Main Menu"));     Serial.println(F("---------"));      Serial.println(F("a) 2's comp Binary to Hex,"));     Serial.println(F("b) 2's comp Binary to Octal,"));     Serial.println(F("c) 2's comp Binary to Decimal,"));     Serial.println(F("d) Octal to 2's comp Binary,"));     Serial.println(F("e) Octal to Hex,"));     Serial.println(F("f) Octal to Decimal,"));     Serial.println(F("g) Hex to 2's comp Binary,"));     Serial.println(F("h) Hex to Octal,"));     Serial.println(F("i) Hex to Decimal,"));     Serial.println(F("j) Decimal to 2's comp Binary,"));     Serial.println(F("k) Decimal to Hex,"));     Serial.println(F("l) Decimal to Octal."));              while (Serial.available ()== 0){}  //Constantly checks to see if anything has been sent over the USB Connection and if it needs to be processed        {          menuselect = Serial.read();          switch (menuselect)           {            case 'a':   //option a) ASCII "a"              Serial.println(F(" "));              Serial.println(F("2's comp Binary to Hex"));                while (Serial.available ()== 0){}                conversion1 = Serial.read();                Serial.println(conversion1);                Serial.println(conversion1, HEX);                delay(2000);                  break;            case 'b':                Serial.println(F(" "));                Serial.println(F("2's comp Binary to Octal"));                while (Serial.available ()== 0){}                conversion2 = Serial.read();                Serial.println(conversion2);                Serial.println(conversion2, OCT);                delay(2000);            break;            case 'c':                 Serial.println(F(" "));               Serial.println(F("2's comp Binary to Decimal"));                while (Serial.available ()== 0){}                conversion3 = Serial.read();                Serial.println(conversion3);                Serial.println(conversion3, DEC);                delay(2000);            break;            case 'd':                 Serial.println(F(" "));               Serial.println(F("Octal to 2's comp Binary"));                while (Serial.available ()== 0){}                conversion4 = Serial.read();                Serial.println(conversion4);                Serial.println(conversion4, BIN);                delay(2000);            break;            case 'e':                 Serial.println(F(" "));              Serial.println(F("Octal to Hex"));                while (Serial.available ()== 0){}                conversion5 = Serial.read();                Serial.println(conversion5);                Serial.println(conversion5, HEX);                delay(2000);            break;            case 'f':               Serial.println(F(" "));               Serial.println(F("Octal to Decimal"));                while (Serial.available ()== 0){}                conversion6 = Serial.read();                Serial.println(conversion6);                Serial.println(conversion6, DEC);                delay(2000);            break;            case 'g':                 Serial.println(F(" "));               Serial.println(F("Hex to 2's comp Binary"));                while (Serial.available ()== 0){}                conversion7 = Serial.read();                Serial.println(conversion7);                Serial.println(conversion7, BIN);                delay(2000);            break;            case 'h':               Serial.println(F(" "));               Serial.println(F("Hex to Octal"));                while (Serial.available ()== 0){}                conversion8 = Serial.read();                Serial.println(conversion8);                Serial.println(conversion8, OCT);                delay(2000);            break;            case 'i':                 Serial.println(F(" "));              Serial.println(F("Hex to Decimal"));                while (Serial.available ()== 0){}                conversion9 = Serial.read();                Serial.println(conversion9);                Serial.println(conversion9, DEC);                delay(2000);            break;            case 'j':                 Serial.println(F(" "));               Serial.println(F("Decimal to 2's comp Binary"));                while (Serial.available ()== 0){}                conversion10 = Serial.parseInt();                Serial.println(conversion10); //Serial.println(" Decimal");                Serial.println(conversion10, BIN); //Serial.println(" Binary");                delay(2000);            break;            case 'k':               Serial.println(F(" "));                Serial.println(F("Decimal to Hex"));                while (Serial.available ()== 0){}                conversion11 = Serial.parseInt();                Serial.println(conversion11);                Serial.println(conversion11, HEX);                delay(2000);            break;            case 'l':                Serial.println(F(" "));                Serial.println(F("Decimal to Octal"));                while (Serial.available ()== 0){}                conversion12 = Serial.parseInt();                 //could have used conversion12 = conversion12 - '0'; when using Serial.read                Serial.println(conversion12);                Serial.println(conversion12, OCT);                delay(2000);            break;           }         }    } }`

kopite

#10
Dec 16, 2012, 12:24 am
Quote
If I read the code correctly you are assuming one or two digit input. What if someone enters 0004?

You are best off:

Collect the input into a buffer, delimited by something (eg. newline)
Do a conversion on that buffer

My link above shows exactly how to do that for decimal numbers, so it shouldn't take weeks to do.

Apologies for my lack of knowledge (as a beginner)-Ive looked at your link but i dont understand exactly what bit (excuse the pun) I should be looking at. I dont exactly understand it all and how i can apply this to my code.

Thanks.

Nick Gammon

#11
Dec 16, 2012, 01:12 am
I've had a go at doing something along those lines. Perhaps it isn't entirely trivial. I don't want to do your homework for you, but the code below partly solves your problem. I'll leave it up to you to flesh out the other input and output bases:

Code: [Select]
`// Example of receiving numbers by Serial// Author: Nick Gammon// Date: 16 December 2012typedef enum { eWantMenu, eWantResponse, eWantFirstDigit, eWantDigit } states;states state = eWantMenu;bool negative = false;long receivedNumber = 0;int inputBase, outputBase;void setup ()  {   Serial.begin (115200);  Serial.println (F("Starting ..."));  } // end of setup  void showNumber ()  {  char buf [20];  ltoa (receivedNumber, buf, outputBase);  Serial.print ("Result = ");  Serial.println (buf);  }  // end of showNumber  void processDigit (byte c)  {  if (c < 0 || c >= inputBase)    {    Serial.print (F("Digit "));    Serial.print ((char) c);    Serial.println (F(" out of range for selected base."));    state = eWantMenu;    return;    }      receivedNumber *= inputBase;  receivedNumber += c;  }  // end of processDigit  void processInput ()  {    byte c = Serial.read ();    if (state == eWantResponse)    {    // ignore spaces, newlines    if (isspace (c))      return;          switch (c)      {              // put other ones here ...            case 'j':   // decimal to binary          inputBase = 10;          outputBase = 2;          break;      case 'k':   // decimal to hex          inputBase = 10;          outputBase = 16;          break;            default:          Serial.println (F("Unknown response."));        state = eWantMenu;        return;      }           receivedNumber = 0;    negative = false;    state = eWantFirstDigit;    Serial.print (F("Enter your number in the base "));    Serial.print (inputBase);    Serial.println (F(" ... "));        return;           }  // end of eWantResponse      // skip spaces, newlines, until we get a digit  if (state == eWantFirstDigit && !isxdigit (c))    return;     state = eWantDigit;    switch (c)    {          case '\n':          showNumber ();         state = eWantMenu;        break;          case '0' ... '9':       processDigit (c - '0');      break;    case 'A' ... 'F':      processDigit (c - 'A' + 10);      break;    case 'a' ... 'f':      processDigit (c - 'a' + 10);      break;          case '-':      negative = true;      break;          } // end of switch    }  // end of processInput  void loop ()  {    if (state == eWantMenu)    {    Serial.println(F("Welcome to my Bin, Dec, Oct, Hex Converter"));    delay(500);    Serial.println(F(" "));    Serial.println(F("Please select a number from the options available..."));    Serial.println(F("*Please Note* The options below are Case Sensitive!"));    Serial.println(F(" "));    Serial.println(F("Main Menu"));    Serial.println(F("---------"));     Serial.println(F("a) 2's comp Binary to Hex,"));    Serial.println(F("b) 2's comp Binary to Octal,"));    Serial.println(F("c) 2's comp Binary to Decimal,"));    Serial.println(F("d) Octal to 2's comp Binary,"));    Serial.println(F("e) Octal to Hex,"));    Serial.println(F("f) Octal to Decimal,"));    Serial.println(F("g) Hex to 2's comp Binary,"));    Serial.println(F("h) Hex to Octal,"));    Serial.println(F("i) Hex to Decimal,"));    Serial.println(F("j) Decimal to 2's comp Binary,"));    Serial.println(F("k) Decimal to Hex,"));    Serial.println(F("l) Decimal to Octal."));     state = eWantResponse;           // throw away any input from before    while (Serial.available ())       Serial.read ();     }      if (Serial.available ())    processInput ();  } // end of loop`

I've used a state machine to know what we are up to (getting a response, getting a number). You'll need to add other input and output bases, and do something with negative numbers.
Please post technical questions on the forum, not by personal message. Thanks!

http://www.gammon.com.au/electronics

kopite

#12
Dec 20, 2012, 10:17 pm
Hi, does anyone know a simple way to read serial input as binary.

To clarify instead of taking an input say number 1 (ascii 49) and reading it as its binary format i want a user to be able to input a binary value say 00101011 in binary format.

Ive tried using byte but when using the serialRead function, quite simply nothing works so ive gone back to the drawing board to see if anyone has a simple solution.

Also how could i take serial read as an octal value, so the user could put in 012 (Dec = 10) and treat it as octal.

Many thanks.

AWOL

#13
Dec 20, 2012, 10:19 pm
Quote
Also how could i take serial read as an octal value, so the user could put in 012

That's an interesting question.
What if you entered 011?
Would you interpret as 3 or 9?
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Nick Gammon

#14
Dec 20, 2012, 10:32 pm
You decided to ask the same question again, huh?

- Moderator
Please post technical questions on the forum, not by personal message. Thanks!

http://www.gammon.com.au/electronics

Go Up

Please enter a valid email to subscribe