4byte array convert to float(c) - c

void OPC_N2_data_read()
{
unsigned int32 iobyte[3][4] = {0x00, };
int32 PM_int[3] = {0x00, };
float PM[3] = {0x00, };
int8 i,j,k;
int8 mask = 0x80;
const int16 mask1 = 0x0001;
const int16 mask0 = 0x0000;
int8 trash_byte = 0x32;
output_bit(ss,1);
output_bit(PM_CLOCK_pin,0);
delay_us (1);
output_bit(ss,0);
delay_us (2);
for( i = 0 ; i < 3 ; i ++ )
{
for ( j = 0 ; j < 4 ; j ++ )
{
for (k = 0 ; k < 8 ; k ++ )
{
output_bit(PM_CLOCK_pin,1);
iobyte[i][j] = iobyte[i][j] << 1;
if ( input ( PM_MISO_pin))
{
iobyte[i][j] |= mask1;
}
else
{
iobyte[i][j] |= mask0;
}
if ((trash_byte & mask) >0)
{
output_high(PM_MOSI_pin);
}
else
{
output_bit(PM_MOSI_pin,0);
}
delay_us(1);
output_bit(PM_CLOCK_pin,0);
delay_us(5);
mask = mask >>1;
}
}
}
delay_us(3);
output_high(ss);
for(i = 0; i<3; i++)
{
PM_int[i] = ((iobyte[i][0]<<24)|(iobyte[i][1]<<16)|(iobyte[i][2]<<8)|(iobyte[i][3]));
PM[i] = *(float*)&PM_int;
}
printf ("%x%x%x%x\r\n",iobyte[0][0],iobyte[0][1],iobyte[0][2],iobyte[0][3]);
printf ("%x%x%x%x\r\n",iobyte[1][0],iobyte[1][1],iobyte[1][2],iobyte[1][3]);
printf ("%x%x%x%x\r\n",iobyte[2][0],iobyte[2][1],iobyte[2][2],iobyte[2][3]);
printf ("%lx,%lx,%lx\r\n", PM_int[0],PM_int[1],PM_int[2]);
printf ("%3.5f,%3.5f,%3.5f\r\n", PM[0],PM[1],PM[2]);
}
I receive data from a 4-byte array.
This data is a float value.
I check through the computer, I see the following.
e911bd41 d867e641 8084e941 e911bd41,d867e641,8084e941 0.00000,0.00000,0.00000
Making the four data into one INT value works fine. PM_int[0],PM_int[1],PM_int[2]
However, if you try to convert this to a float value, only 0.00000 is displayed.
I do not know where the problem is.

Looking on your source code shows that you are assuming that the received iobyte[i][0] to iobyte[i][3] shall be assumed as a float when ordering in big-endian format:
PM_int[i] = ((iobyte[i][0]<<24)|(iobyte[i][1]<<16)|(iobyte[i][2]<<8)|(iobyte[i][3]));
But if you want to convert correctly a 32bits floating-point value, you have to know if the source CPU and the destination CPU are both big-endian or little-endian. Otherwise, it is necessary to reverse the byte order before trying to convert values. So, if your target has a different endianness, replace the above code by the following:
PM_int[i] = ((iobyte[i][3]<<24)|(iobyte[i][2]<<16)|(iobyte[i][1]<<8)|(iobyte[i][0]));
In your source code, an error of the cast formatting between the float PM[i] and the 32bits integer PM_int[i] compute a bad result. The cast must be performed to the good element of the array PM_int[i].
PM[i] = *((float*)&(PM_int[i]));
Instead of:
PM[i] = *(float*)&PM_int;
With the 3 received float values {0xe9, 0x11, 0xbd, 0x41 }, {0xd8, 0x67, 0xe6, 0x41 }, {0x80, 0x84, 0xe9, 0x41 }, the output becomes:
e911bd41
d867e641
8084e941
41bd11e9,41e667d8,41e98480
23.63375,28.80070,29.18970

Related

How to concatenate the hexadecimal data in an array in C

I have my data field as follows DATA = 0x02 0x01 0x02 0x03 0x04 0x05 0x06 0x07 Now I want to concatenate this data as follows DATA = 0x01020304050607. How can I do it using C program. I found a program in C for concatenation of data in an array and the program is as follows:
#include<stdio.h>
int main(void)
{
int num[3]={1, 2, 3}, n1, n2, new_num;
n1 = num[0] * 100;
n2 = num[1] * 10;
new_num = n1 + n2 + num[2];
printf("%d \n", new_num);
return 0;
}
For the hexadecimal data in the array how can I manipulate the above program to concatenate the hexadecimal data?
You need a 64 bit variable num as result, instead of 10 as factor you need 16, and instead of 100 as factor, you need 256.
But if your data is provided as an array of bytes, then you can simply insert complete bytes, i.e. repeatedly shifting by 8 bits (meaning a factor of 256):
int main(void)
{
uint8_t data[8] = { 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
unsigned long long num = 0;
for (int i=0; i<8; i++) {
num <<=8; // shift by a complete byte, equal to num *= 256
num |= data[i]; // write the respective byte
}
printf("num is %016llx\n",num);
return 0;
}
Output:
num is 0201020304050607
Lest say you have input like
int DATA[8] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07};
If you want output like 0x0001020304050607, to store this resultant output you need one variable of unsigned long long type. For e.g
int main(void) {
int DATA[8] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07};
int ele = sizeof(DATA)/sizeof(DATA[0]);
unsigned long long mask = 0x00;
for(int row = 0; row < ele; row++) {
mask = mask << 8;/* every time left shifted by 8(0x01-> 0000 0001) times */
mask = DATA[row] | mask; /* put at correct location */
}
printf("%016llx\n",mask);
return 0;
}
Here's some kind of hack that writes your data directly into an integer, without any bitwise operators:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
uint64_t numberize(const uint8_t from[8]) {
uint64_t r = 0;
uint8_t *p = &r;
#if '01' == 0x4849 // big endian
memcpy(p, from, 8);
#else // little endian
for (int i=7; i >= 0; --i)
*p++ = from[i];
#endif
return r;
}
int main() {
const uint8_t data[8] = { 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
printf("result is %016llx\n", numberize(data));
return 0;
}
This does work and outputs this independently of the endianness of your machine:
result is 0201020304050607
The compile-time endianness test was taken from this SO answer.

Slice up an uint8_t array

Let's say that I have an array of 16 uint8_t as follows:
uint8_t array[] = {0x13, 0x01, 0x4E, 0x52, 0x31, 0x4A, 0x35, 0x36, 0x4C, 0x11, 0x21, 0xC6, 0x3C, 0x73, 0xC2, 0x41};
This array stores the data contained in a 128 bits register of an external peripheral. Some of the information it represents are stored on 2, 3, 8, 12 bits ... and so on.
What is the best and elegant way to slice it up and bit mask the information I need? (The problem is that some things that I need overlaps the length of one cell of the array)
If that can help, this snippet I wrote converts the whole array into a char* string. But casting this into an int is not option because.. well 16 bytes.
int i;
char str[33];
for(i = 0; i < sizeof(array) / sizeof(*array) ; i++) {
sprintf(str+2*i,"%02hX",array[i]);
}
puts(str);
13014E52314A35364C1121C63C73C241
Actually such problem also occures when trying to parse all kind of bitstreams, like video or image files or compressed data by algorithms like LZ*. So the approach used there is to implement a bitstream reader.
But in your case the bit sequence is fixed length and quite short, so one way is to manually check the field values using bitwise operations.
Or you can use this function that I just wrote, which can extract arbitrary number of bits from a uint8 array, starting from desired bit position:
uint32_t extract_bits(uint8_t *arr, unsigned int bit_index, unsigned int bit_count)
{
/* Assert that we are not requested to extract more than 32 bits */
uint32_t result = 0;
assert(bit_count <= sizeof(result)*8 && arr != NULL);
/* You can additionally check if you are trying to extract bits exceeding the 16 byte range */
assert(bit_index + bit_count <= 16 * 8);
unsigned int arr_id = bit_index / 8;
unsigned int bit_offset = bit_index % 8;
if (bit_offset > 0) {
/* Extract first 'unaligned_bit_count' bits, which happen to be non-byte-aligned.
* When we do extract those bits, the remaining will be byte-aligned so
* we will thread them in different manner.
*/
unsigned int unaligned_bit_count = 8 - bit_offset;
/* Check if we need less than the remaining unaligned bits */
if (bit_count < unaligned_bit_count) {
result = (arr[arr_id] >> bit_offset) & ((1 << bit_count) - 1);
return result;
}
/* We need them all */
result = arr[arr_id] >> bit_offset;
bit_count -= unaligned_bit_count;
/* Move to next byte element */
arr_id++;
}
while (bit_count > 0) {
/* Try to extract up to 8 bits per iteration */
int bits_to_extract = bit_count > 8 ? 8 : bit_count;
if (bits_to_extract < 8) {
result = (result << bits_to_extract) | (arr[arr_id] & ((1 << bits_to_extract)-1));
}else {
result = (result << bits_to_extract) | arr[arr_id];
}
bit_count -= bits_to_extract;
arr_id++;
}
return result;
}
Here is example of how it is used.
uint32_t r;
/* Extracts bits [7..8] and places them as most significant bits of 'r' */
r = extract_bits(arr, 7, 2)
/* Extracts bits [4..35] and places them as most significant bits of 'r' */
r = extract_bits(arr, 4, 32);
/* Visualize */
printf("slice=%x\n", r);
And then the visualisation of r is up to you. They can either be represented as hex dwords, characters, or however you decide.

Updating every single block (4bits) with different value in 64 bit unsigned variable?

I have a variable unsigned __int64 text=0x0; and I need to and update each 4 bits with different values.
text = b64b63...b3b2b1b0
I have a loop and inside of the loop must be like this :
for(i=0;i<16;i++)
{
b3b2b1b0=a[0]
b7b6b5b4=a[1]
b11b10b9b8=a[2]
..
..
..
}
I tried this one but didn't work
unsigned __int64 temp=0x0;
unsigned __int64 index=0x0;
for(i=0;i<16;i++)
{
index = (text>>(i*4))&0x0F;
temp = a[index];
text = text | temp<<(i*4);
}
thank you so much
You can use bitshifting and bitwise-OR to do this. Assuming the a[n] values are all between 0 and 15 and also unsigned __int64s:
unsigned __int64 text=0x0;
text = a[0] |
a[1] << 4 |
a[2] << 8 |
etc....;
If you don't trust the a[n] values, use (a[n] & 0xF) to clear all but the four least significant bits before shifting. If a[n] is not an unsigned __int64, cast it before shifting.
You could use bit fields:
typedef struct {
int n0 : 4;
int n1 : 4;
int n2 : 4;
int n3 : 4;
int n4 : 4;
int n5 : 4;
int n6 : 4;
int n7 : 4;
int n8 : 4;
int n9 : 4;
int n10 : 4;
int n11 : 4;
int n12 : 4;
int n13 : 4;
int n14 : 4;
int n15 : 4;
} S64;
typedef union {
uint64_t i;
S64 b;
} U64;
Note: you may need to pay attention to to the endianness of your target platform(s), if you require a specific ordering of the 4 bit fields within the 64 bit value.
If you must use a loop, you can do something like
uint64_t text = 0;
for (int i = 15; i >= 0; --i)
{
text <<= 4;
text |= a[i] & 0x0f; // Masking in case a[i] have more than the lowest four bits set
}
Try the below code. I have tried to copy 0x01, 0x02....0x0f into 16 different nibbles. The code extracts the values and shifts them appropriately combined with the OR operation.
#define NIBBLES 16 /* 64-bit has 16 nibbles */
#define MASK 0x0FLLU
int main()
{
unsigned int val[NIBBLES] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
long long unsigned int num = 0, tmp;
int i, shift = 0;
for (i = 0; i < NIBBLES; i++) {
tmp = (val[i] & MASK) << shift;
num = num | tmp;
shift = shift + 4;
}
printf ("0x%llx\n", num);
}
Output: 0xfedcba9876543210

How to convert a byte array to a integer?

Lets say I have this byte
uint8_t k[8]= {0,0,0,1,1,1,0,0};
Is there a way to get this to become a single integer or hex?
If k represents 8 bytes of the 64-bit integer, go through the array of 8-bit integers, and shift them into the result left-to-right:
uint64_t res = 0;
for (int i = 0 ; i != 8 ; i++) {
res <<= 8;
res |= k[i];
}
The direction of the loop depends on the order in which the bytes of the original int are stored in the k array. The above snippet shows the MSB-to-LSB order; if the array is LSB-to-MSB, start the loop at 7, and go down to zero.
If the bytes represent individual bits, shift by one rather than eight.
This should do the trick:
int convertToInt(uint8_t k[8], bool leastSignificantFirst) {
int res = 0;
for (int i = 0; i < 8; ++i) {
if (leastSignificantFirst) {
res |= (k[i] & 1) << (7 - i);
} else {
res |= (k[i] & 1) << i;
}
}
return res;
}

How to convert a byte array to an int array?

I'm using a dsPic33F (16 bit microcontroller);
How to convert char[] to int[] such that every two chars becomes an int using C++?
and the inverse operation?
int* intArray = new int[sizeOfByteArray];
for (int i=0; i<sizeOfByteArray; ++i)
intArray[i] = byteArray[i];
Or
std::copy(byteArray, byteArray+sizeofByteArray, intArray);
I guess you want to combine packs of bytes into int?
what you need to do is to shift the bits when you create your int
(oki this is java because I don't have my C ++ code here)
public static final int byteArrayToInt(byte [] b) {
return (b[0] << 24)
+ ((b[1] & 0xFF) << 16)
+ ((b[2] & 0xFF) << 8)
+ (b[3] & 0xFF);
}
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
this logic works with any conversion formats as long as you know the length of your variables
On a dsPIC 33F, I doubt you're using C++. If you are using C++, what compiler are you using, and how much of a runtime library do you have? (And where did you get it!)
If the byte ordering is correct, you can just use memcpy() if you need a copy, or just cast the pointer if you just want to use the 16 bit numbers in the buffer and the alignment is OK. If you are managing the buffer, it is not unusual to use a union for this kind of requirement on a platform like this:
union my_buffer {
unsigned char char_buf[128];
int int_buf[64];
};
Access through char_buf when dealing with characters, access through int_buf when dealing with ints.
If the bytes need to be swapped, just implement a variant of swab() and use it instead of memcpy(), something like the other answers, or some code like this:
void doit(int16_t* dest, char const* src, size_t word_count)
{
char* const end = (char*) (dest + word_count);
char* p;
for (p = (char*) dest; p != end; src += 2, p += 2) {
p[0] = src[1];
p[1] = src[0];
}
}
I'm not sure if your byte mean char or octet. You may have octets already packed by two in dsPIC's 16-bit words so you have no more to pack them.
#include <limits.h>
#include <stddef.h>
#define BYTE_BIT CHAR_BIT /* Number of significant bits in your 'byte' * Read note below */
/* pack routine */
void ipackc(int *packed, const char *unpacked, size_t nints) {
for(; nints>0; nints--, packed++, unpacked += 2) {
*packed = (unpacked[0]<<BYTE_BIT) | (unpacked[1] & ((1<<BYTE_BIT)-1));
}
}
/* unpack routine */
void cunpacki(char *unpacked, const int *packed, size_t nints) {
for(; nints>0; nints--, packed++, unpacked += 2) {
unpacked[0] = *packed>>BYTE_BIT;
unpacked[1] = *packed & ((1<<BYTE_BIT)-1);
}
}
That's a C code, but there's nothing to deal with C++ features. It compilable in C++ mode. You may replace limits.h and stddef.h with climits and cstddef for tighter C++ conformance.
Note: This code will not work if 2 your 'bytes' cannot fit into int. Check this. Number of bits in int should be not less that 2*BYTE_BIT or one of chars will be lost. If you mean 8-bit octet under 'byte', you may change CHAR_BIT in BYTE_BIT definition to just 8, and then 16-bit int will fit octets correctly.
Note about implementation:
((1<<BYTE_BIT)-1)
is a bit mask for N lower bits, where N=BYTE_BIT. It equal
/--N--\
...011...11 (binary)
I'm assuming that your char array contains bytes (instead of actual ascii characters), which you want to convert into 16-bit signed integers. The function below will work for MSB-first byte ordering. I used unsigned chars here to represent the byte input (uint8_t).
void BytesToInts(uint8_t *byteArray, uint16_t byteArraySize, int16_t *intArray, uint16_t intArraySize) {
//do some error checking on the input
if (byteArraySize == 0) return;
if (intArraySize != (byteArraySize/2)) return;
//convert each pair of MSB-first bytes into a signed 16-bit integer
for (uint16_t i=0; i<intArraySize; i++)
{
intArray[i] = (int16_t) ((byteArray[i<<1]<<8) | byteArray[(i<<1)+1]);
}
}
If you need the integer definitions, you can use something like this:
typedef unsigned short uint16_t;
typedef signed short int16_t;
typedef unsigned char uint8_t;
Here is a compiled and tested method:
#include <stdio.h>
unsigned short ByteToIntArray(
unsigned char inByteArray[],
unsigned short inArraySize,
unsigned short outWordArray[],
unsigned short outArraySize,
unsigned char swapEndian
)
{
if ( ( inArraySize/2 > outArraySize )
|| ( outArraySize == 0 )
|| ( inArraySize == 0 )
)
{
return -1;
}
unsigned short i;
if ( swapEndian == 0 )
{
for ( i = 0; i < outArraySize; ++i )
{
outWordArray[ i ] = ( (unsigned short)inByteArray[ i*2 ] << 8 ) + inByteArray[ i*2 + 1 ];
}
}
else
{
for ( i = 0; i < outArraySize; ++i )
{
outWordArray[ i ] = ( (unsigned short)inByteArray[ i*2 + 1 ] << 8 ) + inByteArray[ i*2 ];
}
}
return i;
}
int main(){
unsigned char ucArray[ 16 ] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
unsigned short usArray[ 8 ];
unsigned short size;
// "/ 2" on the usArray because the sizes are the same in memory
size = ByteToIntArray( ucArray, sizeof( ucArray ), usArray, sizeof( usArray ) / 2, 0 );
if( size > 0 )
{
printf( "Without Endian Swapping:\n" );
for( unsigned char i = 0; i < size ; ++i )
{
printf( "0x%04X ", usArray[ i ] );
}
printf( "\n" );
}
if( size > 0 )
{
// "/ 2" on the usArray because the sizes are the same in memory
size = ByteToIntArray( ucArray, sizeof( ucArray ), usArray, sizeof( usArray ) / 2, 1 );
printf( "With Endian Swapping:\n" );
for( unsigned char i = 0; i < size ; ++i )
{
printf( "0x%04X ", usArray[ i ] );
}
printf( "\n" );
}
return 0;
}
The ByteToIntArray takes 5 parameters and returns the size of the actual converted array, this is handy if you pass in outWordArray that is bigger then the actual converted size and at the same time serves as a way to pick up errors.
A simple bit-wise shift operator and + is used for combining the two bytes into one word.
I just used printf to test the procedures and I'm aware that to use this in embedded hardware usually takes allot of code space. And I just included Endian swapping to make sure you can see what you need to do in both cases but this can easily be removed in your actual implementation.
There is also lot of room for optimization in the ByteToIntArray routine but this way it is easy to understand.

Resources