Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Protable way of reading str[4] as uint32_t Date: Mon, 30 Mar 2020 19:04:32 -0700 Organization: None to speak of Lines: 38 Message-ID: <875zeluvnz.fsf@nosuchdomain.example.com> References: <40d1f926-8737-4332-93f2-c37c46f731f9@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: reader02.eternal-september.org; posting-host="dbc073e31c3669f15dacaa958203e3d4"; logging-data="29477"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19DxnbyQ7KUleQ+IKBpZVRB" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/26.3 (gnu/linux) Cancel-Lock: sha1:zyvorG+07Qkc28xDiOhXSVYpfQk= sha1:QPfICFaGpyJchahWbtpa84ky3Qk= Xref: csiph.com comp.lang.c:150919 Richard Damon writes: > On 3/30/20 2:42 PM, wyniijj@gmail.com wrote: >> I'd like to read the value a.value in the following program as 0x78563412 in a >> portable way, none of hton or ntoh is useful. How should I do? >> >> #include >> #include >> >> int main() >> { >> union { >> char str[4]; >> uint32_t value; >> } a; >> >> a.str[0]=0x12; >> a.str[1]=0x34; >> a.str[2]=0x56; >> a.str[3]=0x78; [...] > Network order is Big Endian, your problem statement defines decoding > little endian, so the network order functions won't work. > > In my mind the simplest is: > > a.ser[0] | (a.str[1] << 8) | (a.str[2] << 16) | (a.str[3] << 24) > > i.e., be explicit and access by bytes in the order you want. And definitely use unsigned char rather than char, and test with values exceeding 0x7f. [...] -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com Working, but not speaking, for Philips Healthcare void Void(void) { Void(); } /* The recursive call of the void */