Help with converting a byte to an integer from DAC register

Hi

I have built a circuit where I am communicating with a DAC and reading data from the registers.

I am struggling to convert the 1 byte read into an int so i can then divide it which will lead to a float.

I read the byte as follows:

Serial.println("\Requesting Data From 18...");
Wire.beginTransmission(CHIP_ADDRESS_READ);
Wire.write(0x18);
Wire.endTransmission();
Wire.requestFrom(CHIP_ADDRESS_READ, 1); // We want one byte
byte valEighteen = Wire.read();
Serial.println("\Value Read...Hex");
Serial.println("");
Serial.println(valEighteen, HEX);
Serial.println(valEighteen, BIN);
Serial.println(valEighteen, DEC);
Serial.println("\Bit rate");

So lets say I read 0x10 or in binary 00010000 which would be 16 in decimal

How can I take this byte (valEighteen) and convert it to an integer?

The reason I want to convert it to an int is so then I can apply (64/x)*48000

So in this example 64/16 = 4 then 4*48000=192,000khz

However some numbers could be floats, for example if I read 0x23 this would be 35 decimal so
64/35 = 1.8 then 1.8*48000=86,400khz and this is where I get a bit lost

I'm not sure this is the best way is to do this, I am attracted to ints/floats because I find them easier to work with and more natural to understand!

Any help would be greatly welcomed!

Thank you

A byte is an integer

float result = other_number/((float)valEighteen);

The problem is that the compiler defaults to integer math, so (64/x) will lose the decimal part before the multiplication with 48000. If you want a float, use (64.0/x)*48000.0

If you want the answer as an integer, then 48000L * 64L / x will do the math using 32-bit integers.

Hi

Thanks for your very helpful response

Given the example I provided above how would you do this?

Should I walk through each bit in the byte doubling my multiplcation as i go? That would be one way but I was hoping there was a simple solution

I undertand that the byte is an int in the sense that it is a whole number but how do I convert the byte so it can be used with functions such as "int"?

1 Like

You do not have to do anything as far as converting the byte into an int - it is already an 8-bit unsigned int, the compiler will handle the conversion to a larger format 16-bit int for the math. Your problem is that (64/35) = 1, not 1.8, any fractional part is truncated because the math is done as integer math.

Hi

Yup thats whats happening

Given the function

float bitRate = (64/(valEighteen));

I get
100011
35
Bit rate
1.00

What is the best method to have it so I can get the 1.8 rather than it trucating to 1.00?

Thank you

Two have been provided. Read the responses carefully, then try them.

Hi

All working now thank you for your help

float bitRate = 64/((float)valEighteen);
bitRate = bitRate*48000;
Serial.println(bitRate);