Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: convert unsigned long long into char[4] |
| Date | 2015-11-25 11:54 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <8737vui9a1.fsf@bsb.me.uk> (permalink) |
| References | <n32sd3$qjh$1@dont-email.me> <83f3a05d-3535-4791-9c8a-aa92b57178cd@googlegroups.com> |
Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> On Tuesday, November 24, 2015 at 11:40:48 PM UTC, bilsch01 wrote:
>> See the code below. The function d2hx takes a 4 digit hex number 0xfffe
>> and converts it into ascii bytes returned in unsigned long long
>> 'answer'. The contents of answer is 0x46464645
>> where 0x46 = 'F' and 0x45 = 'E'
<snip>
> unsigned long long d2hx(int dc)
> {
> char hex[5];
> int i;
> unsigned long long answer = 0;
> assert(dc >= 0 && dc <= 0xFFFF);
>
> for(i=0;i<4;i++)
> {
> hex[i] = "0123456789abcdef"[(dc >> ((3-i) * 4)) & 0xF];
(The OP wants "ABCDEF".)
> }
> hex[i] = 0;
> memcpy(&answer, hex, 5);
That might not produce the value the OP wants. By writing 0x46464645
there is an indication that the result should be a specific integer
value.
If that's the case, I'd do it by arithmetic rather than memcpy:
answer = (answer << 8) + "0123456789ABCDEF"[(dc >> (3-i) * 4) & 0xF];
> return answer;
> }
>
> int main(){
> int dc = 0xfffe;
> unsigned long long answer;
>
> answer = d2hx(dc);
> // bug here, add the &
> printf("answer = %s\n", &answer);
It's not clear what the bug is. It might be that the op intended to
print a hex value rather than a string. Also, though it's rare to care
about portability in code like this, you should a cast to that argument
or all bets are, technically, off. It's undefined behaviour as it is.
> return 0;
> }
--
Ben.
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
convert unsigned long long into char[4] bilsch01 <king621@comcast.net> - 2015-11-24 15:40 -0800
Re: convert unsigned long long into char[4] Barry Schwarz <schwarzb@dqel.com> - 2015-11-24 17:21 -0800
Re: convert unsigned long long into char[4] bilsch01 <king621@comcast.net> - 2015-11-24 18:10 -0800
Re: convert unsigned long long into char[4] Keith Thompson <kst-u@mib.org> - 2015-11-24 18:18 -0800
Re: convert unsigned long long into char[4] Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-11-25 00:23 -0800
Re: convert unsigned long long into char[4] Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-11-25 11:54 +0000
Re: convert unsigned long long into char[4] bilsch01 <king621@comcast.net> - 2015-11-25 11:35 -0800
Re: convert unsigned long long into char[4] Jorgen Grahn <grahn+nntp@snipabacken.se> - 2015-11-28 22:06 +0000
csiph-web