Share your knowledge at the LQ Wiki.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 07-29-2009, 03:44 AM   #1
Registered: Jul 2009
Posts: 50

Rep: Reputation: 16
Question how to assign a u_short variable to a u_char array ?


How can I assign a u_short variable to a u_char array ?

Old 07-29-2009, 06:15 AM   #2
Senior Member
Registered: Jan 2005
Location: Melbourne, Australia
Distribution: Debian Stretch (Fluxbox WM)
Posts: 1,389
Blog Entries: 52

Rep: Reputation: 355Reputation: 355Reputation: 355Reputation: 355
I'm assuming you are using C, not C++:

logical method
u_short a = 0x4567;
u_char b[sizeof(u_short)], *pB = b;
while (pB < b+sizeof(u_short))
	*pB++ = a&0xFF;
	a >>= 8;
// gives array b[]
union method
u_short a = 0x4567;
	u_short a1;
	u_char b[sizeof(u_short)];
} both;
both.a1 = a;
// gives array both.b[]
casting method
u_short a = 0x4567;
u_char *b = (u_char *) &a;
// gives array b[]
1. watch out for byte order issues (some architectures have high byte first), which affect the second two methods
2. the size of a u_short is not necessarily the same between different architectures or compilers

The first method is not as cpu time expensive as it looks, and the semantics are better defined.

Last edited by neonsignal; 07-29-2009 at 06:17 AM.


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
How do you assign a variable to be a variable file name in a directory? David_Elliott Programming 4 04-14-2009 10:19 AM
Bash Variable Array, Trying to add another value into the array helptonewbie Linux - Newbie 6 03-02-2009 11:18 PM
How to assign a string to a structure variable in C? daYz Programming 7 06-13-2007 02:38 PM
How can I assign to a pointer array like char *args[]; ? haydari Programming 3 04-09-2007 11:48 PM
Cannot assign NULL to array? exvor Programming 7 10-31-2006 01:00 PM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:07 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration