converting a char to short, int, etc

Posted on 2006-04-30
Last Modified: 2009-12-16
I know a char is 1 byte, short is 2 byte, long 4 byte. The program I am writing stores data 1 byte at a time in an array. Now is there a way to take 2 bytes of data and convert it to a short? And is there a way to take a short and convert it to 2 1 byte chars and store them in a char[2] array?

C Code would help me. Thank you for your time.
Question by:Linky
    LVL 45

    Accepted Solution

    Hi Linky,

    When you move data from a char, short, int, or long to another variable of any of these types, C does the conversions for you.  If you're moving something that's too long, C truncates to the left.  If the new field is longer, C sign extends so that the true value is copied.

    But I think that you want to do something just a bit different.  You seem to want to move the bytes of an integer to a character array, and back again.

    The only real trick is to use UNSIGNED values.  The sign bit gets very tricky!  But that's OK.  If the value is signed, recasting will work.  But it's easier to see if you start with unsigned values.  Oh.  The char array MUST be unsigned.

    char Array[2];
    int    Value;

      Array[0] = Value;
      Array[1] = Value >> 8;

    // And going the other way

      Value = (Array[1] << 8) | Array[0];

    Good Luck!
    LVL 2

    Author Comment

    Unsigned values won't be a problem. Thank you.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
    This tutorial is posted by Aaron Wojnowski, administrator at  To view more iPhone tutorials, visit This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
    The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
    Video by: Grant
    The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now