U
U
UltimateOrb2015-06-14 17:40:04
Programming
UltimateOrb, 2015-06-14 17:40:04

How to convert an unsigned number to 4 bytes?

The essence of the problem is that this must be done without the use of shifts and bitwise operations. I managed to quickly find an algorithm for converting a number into 2 bytes.

word x=8800; // = 0x2260

byte a=x/256;
byte b=x%256;

It seems to me that here you need to somehow use the value 16 777 216 for high bytes.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
maaGames, 2015-06-14
@UltimateOrb

That's why institute education (programmer) is useless, because they force you to use division where you need to use shifts and binary operations.
On the subject, you think correctly:
low byte = x% 256
first byte = (x / 256)% 256
second byte = (x / (256 * 256))% 256
high byte = x / (256 * 256 * 256)

R
Rsa97, 2015-06-14
@Rsa97

What language is it?
For C/C++

long val = 0x12345678;
printf("long: %ld\n", val);
printf("short: %d %d\n", ((short *)(&val))[0], ((short *)(&val))[1]);
printf("char: %d %d %d %d\n", ((char *)(&val))[0], ((char *)(&val))[1], ((char *)(&val))[2], ((char *)(&val))[3]);

or via union
union {
    long l;
    short s[2];
    char c[4];
} val;
long val.l = 0x12345678;
printf("long: %ld\n", val.l);
printf("short: %d %d\n", val.s[0], val.s[1]);
printf("char: %d %d %d %d\n", val.c[0], val.c[1], val.c[2], val.c[3]);

A
Alexander, 2015-06-21
@AlanDrakes

C:
val = 0x1234;
a = (val & 0xFF);
b = (val >> 8);
Oops!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question