E
E
evg_962018-04-12 12:07:42
C++ / C#
evg_96, 2018-04-12 12:07:42

How to display each byte of an int value?

It was necessary to output each byte of an int value.

int value = 257;

for (int i = 0; i < sizeof(int); i++)
  printf("%hhd ", *(((char *) &value) + i)); // 1 1 0 0

Where do negative numbers come from in the answer? For example, if you use a number 1234, then in my case the output will be equal to-46 4 0 0

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Makarov, 2018-04-12
@evg_96

1. char is a signed type. Use unsigned char, and preferably std::byte if available to you.
2. check the format string.

R
res2001, 2018-04-12
@res2001

1234 in 4D2 hexadecimal system.
The low byte is equal to D2, in binary it is: 1101 0010
As you can see, the high bit is set to 1 - which means that if this is a signed number, then it is negative and encoded in two's complement . It remains only to decompose D2 in an additional code and get -46 - this is the result for you and printed f.

A
Aliaksei Trafimchyk, 2014-03-12
@AT547

try overriding the getItemId() method on the adapter

@Override
  public long getItemId(int position) {
    return <ваш_правильный_id>;
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question