# split int value into bytes

Hello,
i'm interfacing to a 10-bit I2C DAC that requires it's data to be sent into 2 bytes, MSB and LSB, but they're "shifted".
i.e.: 1023 is [0000 0011]MSB [1111 1111]LSB
but the DAC is "shifted" towards the MSB, and expects 1023 as [1111 1111]MSB [11xx xxxx]LSB which is dec 65472, x are don't care(i'll set to 0).

so, the question in hand:
¿how do i split an int into 2 bytes for my DAC?(i.e., splitting them).
my initial idea is:

``````uint value = 1023                          //if signed when i shift the MSb will cause negative result
value = value << 8                         //shift value to teh right, result is 65472d for my DAC
byte MSB = (value & 0xFF00) >> 8   //mask LSB, shift 8 bits to the right
byte LSB = value & 0x00FF             //mask MSB, no need to shift
``````

then use those two bytes in whatever command i want, is there a better way to write the uint directly without my byte split?.
Also, do i need to declare type after the equal?, like byte MSB = byte((value & 0xFF00) >> 8).

Regards

What is the order of bits in the LSB?
Is that reversed too?
(hard to tell from your example)

I think you can use `highByte(value)` and `lowByte(value)` - these are defined in wiring.h at least.

You also meant `value = value << 6` in the second line surely?

AWOL:
the order is MSb to LSb
dunno how to clarify it.... letsee
DAC expectes a 10 bit data, D0 to D9 in 2 bytes
first byte is MSB containing: [D9 D8 D7 D6 D5 D4 D3 D2]
second byte is LSB [D1 D0 X X X X X]

MarkT:
I think you can use `highByte(value)` and `lowByte(value)` - these are defined in wiring.h at least.

You also meant `value = value << 6` in the second line surely?

no, i meant 8, i’m shifting a full byte left, thus 8 places.

i’ll try those functions, never knew they existed

i'll try those functions, never knew they existed

Neither did I - just grepped the source for likely names.

here's what they do:

``````#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))
``````

essentially the lowbyte is what i was doing anyway(but the first 00 in 0x00FF is not necessary)
the highbyte, it doesn't wastes time masking it with bitwise and, just shifts it and done, i was masking before i didn't know how would the compiler react to an overflow but now that i think about it, it's unnecessary as i'm discarding the LSB.

i'll use those funcs then, no need to reinvent the wheel