|
-
February 2nd, 2007, 04:11 PM
#1
conversion from int to char
Hi,
I am trying to write to a binary file and while I am setting the values I have to convert an int to a char using
rec.cStopReason = (char) m_nStopCode; where the defnitions are as follows.
char cStopReason; //25
int m_nStopCode;
For all the values in m_nstopcode it works fine but when I have the value as 128 in m_nstopcode I get cStopReason as -128.
Can anyone help me understand why it is doing that.
Thanks,
Pushpa.
-
February 2nd, 2007, 04:27 PM
#2
Re: conversion from int to char
its because you are using a signed char. If you will not have negative values, unsigned char is better and have twice the positive range of a signed char.
-
February 2nd, 2007, 04:30 PM
#3
Re: conversion from int to char
On most computers, a char can only range from -128 to 127.
-
February 2nd, 2007, 05:38 PM
#4
Re: conversion from int to char
Code:
rec.cStopReason = (unsigned char) m_nStopCode;
-
February 2nd, 2007, 06:06 PM
#5
Re: conversion from int to char
 Originally Posted by Skizmo
Code:
rec.cStopReason = (unsigned char) m_nStopCode;
You think this will work?:
Code:
char cStopReason;
int m_nStopCode = 128;
cStopReason = (unsigned char) m_nStopCode;
cStopReason is still a signed char, hence it cannot handle the value of 128 and will wrap over to -128!
To make this work you'll need to declare cStopReason as unsigned char;
Code:
unsigned char cStopReason; //25
int m_nStopCode = 128;
cStopReason = (unsigned char) m_nStopCode;
Best regards,
Laitinen
Last edited by laitinen; February 2nd, 2007 at 06:10 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|