The functions cfsetospeed
and cfsetispeed
take baud rate as type speed_t
:
int cfsetispeed(struct termios *termios_p, speed_t speed);
int cfsetospeed(struct termios *termios_p, speed_t speed);
The type speed_t
is basically an integer, but casting is not a solution, as can be seen from the baudrate definitions in termios.h
:
#define B0 0x00000000
#define B50 0x00000001
#define B75 0x00000002
// ...
#define B9600 0x0000000d
#define B19200 0x0000000e
#define B38400 0x0000000f
When I process user input (e.g. from file), I convert a string such as "9600" to integer 9600, and then to B9600. I'm basically looking for a generic way to convert the following:
// 0 -> B0
// 50 -> B50
// 75 -> B75
// ...
// 9600 -> B9600
// 19200 -> B19200
// 38400 -> B38400
One way to convert from int
(such as 9600) to speed_t
(such as B9600) is a switch-case structure. Is there a better way to achieve this?
speed_t baudrate(int br) { ... }
, then your code looks quite elegant withcfsetispeed(term, baudrate(19200));
or similar.... – Precipitateint
to hold the value of the baud except when you are sure all the platforms your code will ever run on have a large enoughint
. also, a baud rate can not be negative. Better would beuint_fast32_t
,uint_least32_t
,unsigned long
oruint32_t
(when you are sure this type exist, which is almost everywhere the case). – Niobous