From: Phil Sutter <phil@nwl.cc>
To: Randi Botse <nightdecoder@gmail.com>
Cc: linux-c-programming <linux-c-programming@vger.kernel.org>
Subject: Re: Pointer to a char
Date: Tue, 18 Sep 2012 12:29:56 +0200 [thread overview]
Message-ID: <20120918102956.GA14000@orbit.nwl.cc> (raw)
In-Reply-To: <CAA6iF_7=j6J+wOyYcQgwvSO1dG92kVNcJcYXFY7BiiRZ4d0UKQ@mail.gmail.com>
Hi,
On Tue, Sep 18, 2012 at 04:29:32PM +0700, Randi Botse wrote:
> ...
> char *p;
> unsigned int i = 0xcccccccc;
> unsigned int j;
>
> p = (char *) &i;
> printf("%.2x %.2x %.2x %.2x\n", *p, p[1], p[2], p[3]);
>
> memcpy(&j, p, sizeof(unsigned int));
> printf("%x\n", j);
> ...
>
> Output:
>
> ffffffcc ffffffcc ffffffcc ffffffcc
> 0xcccccccc
>
>
> My questions are:
>
> 1. Why it prints "ffffffcc ffffffcc ffffffcc ffffffcc"? (if p is
> unsigned char* then it will print correctly "cc cc cc cc")
This is because of the two's complement in which singed absolute values
are stored internally. Since %x is a conversion of an integer, signed
extension of the passed char happens, which in two's complement means
that the leading bit is replicated to fill the upper bits. (0xC is 1100
in binary).
> 2. Why pointer to char p copied to j correctly, why not every member
> in p overflow? since it is a signed char.
I am not quite sure about what the question is here (maybe caused by the
lack of verbs in your sentence). Keep in mind that memcpy() only copies
the memory, irrespective of the pointer type passed. Also,
sizeof(unsigned int) == sizeof(int).
HTH, Phil
next prev parent reply other threads:[~2012-09-18 10:29 UTC|newest]
Thread overview: 7+ messages / expand[flat|nested] mbox.gz Atom feed top
2012-09-18 9:29 Pointer to a char Randi Botse
2012-09-18 10:29 ` Phil Sutter [this message]
2012-09-18 10:33 ` Duan Fugang-B38611
2012-09-19 1:04 ` Jon Mayo
2012-09-19 7:59 ` Randi Botse
2012-09-19 8:47 ` Leon Shaw
2012-09-19 18:09 ` Jon Mayo
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20120918102956.GA14000@orbit.nwl.cc \
--to=phil@nwl.cc \
--cc=linux-c-programming@vger.kernel.org \
--cc=nightdecoder@gmail.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).