Path: csiph.com!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: Tue, 31 Mar 2020 10:59:10 -0700 Organization: None to speak of Lines: 36 Message-ID: <871rp8v21d.fsf@nosuchdomain.example.com> References: <40d1f926-8737-4332-93f2-c37c46f731f9@googlegroups.com> <875zeluvnz.fsf@nosuchdomain.example.com> <98d5d7c7-8d0f-40e8-b2bf-bdac3d1ac846@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Info: reader02.eternal-september.org; posting-host="dbc073e31c3669f15dacaa958203e3d4"; logging-data="21358"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+eGTsqVd+Vr98pYz+CcTVi" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/26.3 (gnu/linux) Cancel-Lock: sha1:zL3hD3W/WuPNRJna5Ez+dt2LZec= sha1:WGHWo9PEsjTf12iSdVBDvlhr1PY= Xref: csiph.com comp.lang.c:150930 wyniijj@gmail.com writes: > Keith Thompson於 2020年3月31日星期二 UTC+8上午10時04分43秒寫道: [...] >> And definitely use unsigned char rather than char, and test with values >> exceeding 0x7f. [...] > Yes, the type str should be uint8_t. Should I write it > > union { > uint8_t str[4]; > uint32_t value; > } a; > > a.str[0]='\x12'; > a.str[1]='\x34'; > a.str[2]='\x56'; > a.str[3]='\x78'; > > uint32_t b=(uint32_t)a.str[0] | ((uint32_t)a.str[1]<<8) | ((uint32_t)a.str[2] << 16) | ((uint32_t)a.str[3] << 24); > > a.value is useless. No. You've said elsewhere that the str array contains a UTF-8 encoding of a character (something you didn't initially mention). The code above would be a way of interpreting the byte sequence { 0x12, 0x34, 0x56, 0x78 } as the integer value 0x12345678 -- but the way UTF-8 characters are encoded is very different from that. https://en.wikipedia.org/wiki/UTF-8 -- 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 */