[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


converting a char to short, int, etc

Posted on 2006-04-30
Medium Priority
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 46

Accepted Solution

Kent Olsen earned 200 total points
ID: 16574711
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!

Author Comment

ID: 16574757
Unsigned values won't be a problem. Thank you.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
Suggested Courses

873 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