LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
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 Bookworm (Fluxbox WM)
Posts: 1,391
Blog Entries: 54

Rep: Reputation: 360Reputation: 360Reputation: 360Reputation: 360
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



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 to assign a string to a structure variable in C? daYz Programming 10 07-06-2022 11:07 AM
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 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

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 12:25 AM.

Main Menu
Advertisement
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
Open Source Consulting | Domain Registration