Click to See Complete Forum and Search --> : C++: Convert a char to a short


Cerf
05-31-2004, 10:33 PM
Yo yo yo

I was just wondering, how can I convert a char to a short in C++

maccorin
05-31-2004, 10:36 PM
char c = 'b';
short int i = (short)c;


you don't even really need the typecast, just 'i = c' will work... but you may get a warning

Cerf
05-31-2004, 10:46 PM
Originally posted by maccorin

char c = 'b';
short int i = (short)c;


you don't even really need the typecast, just 'i = c' will work... but you may get a warning

I have found that it is alittle more complex then that


#include <stdio.h>
#include <unistd.h>
#include <sys/io.h>
#include <iostream.h>

#define BASEPORT 0x378 /* lp1 */

int main(int argc, char* argv[])
{
ioperm(BASEPORT, 3, 1);

// cout << argc << endl;

if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
outb((int)argv[i], BASEPORT);
cout << (int)argv[i] << endl;
}
}else{
for (int i = 0; i < 256; i++)
{
outb(i, BASEPORT);
usleep(1);
}
}
ioperm(BASEPORT, 3, 0);
}



Take a look at the result, it should say 0 (not a string but an integer)

[root@localhost parallelport]# ./parallelport 0
-1073743196

maccorin
05-31-2004, 10:51 PM
first of all, argv[1], is a pointer to a char (ie... string) not a char, second i though you just wanted to convert 'a' or something ascii equivelant and store it in a short (no conversion really....)

your looking for atoi


man 3 atoi

madcompnerd
05-31-2004, 11:39 PM
I just ran a test of it, it compiles and works.
A short should be at least the size of a char and less than an int from my quick googling. So the switch should work fine for all normal ascii values, although you may want to check your compiler or use unsigned shorts for those larger chars.
Edit:
I'm referring to the simple conversion:
short var = short(char);

maccorin
05-31-2004, 11:46 PM
unless he's on a 16bit computer the signed/unsigned won't matter...

on x86:
short == 2 bytes (16 bits)
long/int == 4 bytes (32 bits)
char == 1 byte (8 bits) on _all_ architectures

Cerf
06-01-2004, 04:16 PM
Originally posted by maccorin
first of all, argv[1], is a pointer to a char (ie... string) not a char, second i though you just wanted to convert 'a' or something ascii equivelant and store it in a short (no conversion really....)

your looking for atoi


man 3 atoi


ator worked properly for me, thanks