LinuxQuestions.org
Support LQ: Use code LQ3 and save $3 on Domain Registration
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
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.

Notices

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

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


Hi,

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

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

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

logical method
Code:
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
Code:
u_short a = 0x4567;
union
{
	u_short a1;
	u_char b[sizeof(u_short)];
} both;
both.a1 = a;
// gives array both.b[]
casting method
Code:
u_short a = 0x4567;
u_char *b = (u_char *) &a;
// gives array b[]
Caveats:
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.
 
  


Reply


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


All times are GMT -5. The time now is 10:33 AM.

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