CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Nov 2003
    Posts
    107

    Unhappy 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.

  2. #2
    Join Date
    May 2006
    Location
    Norway
    Posts
    1,709

    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.

  3. #3
    Join Date
    Apr 2004
    Location
    England, Europe
    Posts
    2,492

    Re: conversion from int to char

    On most computers, a char can only range from -128 to 127.
    My hobby projects:
    www.rclsoftware.org.uk

  4. #4
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: conversion from int to char

    Code:
    rec.cStopReason = (unsigned char) m_nStopCode;

  5. #5
    Join Date
    May 2006
    Location
    Norway
    Posts
    1,709

    Re: conversion from int to char

    Quote 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
  •  





Click Here to Expand Forum to Full Width

Featured