1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

int (32bit)配列 を ポインターとメモリー操作を使って byte に分割(戻しも)

Last updated at Posted at 2025-01-16

x M5NanoC6での予定は、未定

目的
int(32ビット)2個の配列を
符号なし8ビットの配列の電文(パケット(フレーム))に
変換する

いろいろ
メモリー操作での変換は、オーバーヘッドが多すぎて
あまり、好きでは、ないが、項目が増えた場合は、しょうがないので
他の人が多くやる様にポインターの強制キャストで変換
ビットシフト操作は、いろいろ指摘も受けたし
もう少し、工夫が必要!!!
c言語の場合は、9割がた、メモリー操作なんだけど、いろいろ、わすれた

オンラインコンパイラ paiza



#include <iostream>
using namespace std;
int main(void){
    // Your code here!
    
    printf("START\n");
    
    //送信バッファー int(32bit)配列
    unsigned char ac[256+1];
    
    unsigned char *c;
    
    int s[2];
    
    s[0] = -2;    //センサーの値
    s[1] = -3;    //センサーの値

    printf("[%d],[%d]\n",s[0],s[1]);

    c = (unsigned char *)(&s[0]);
    ac[0+0]=c[0+0];
    ac[0+1]=c[0+1];
    ac[0+2]=c[0+2];
    ac[0+3]=c[0+3];
   
    ac[4+0]=c[4+0];
    ac[4+1]=c[4+1];
    ac[4+2]=c[4+2];
    ac[4+3]=c[4+3];
 
    
    
    printf("[%x][%x][%x][%x]\n",ac[0],ac[1],ac[2],ac[3]);
    printf("[%x][%x][%x][%x]\n",ac[4],ac[5],ac[6],ac[7]);

    
    int *p;
    p = (int *)(&ac[0]);
    s[0] = *p; //メモリコピー
    
    p = (int *)(&ac[4]);
    s[1] = *p; //メモリコピー

    printf("\n");
    printf("[%d],[%d]\n",s[0],s[1]);
    
}



START
[-2],[-3]
[fe][ff][ff][ff]
[fd][ff][ff][ff]

[-2],[-3]


いろいろ工夫

memcpyを使用する



#include <iostream>
#include <string.h>
using namespace std;
int main(void){
    // Your code here!
    
    printf("START\n");
    
    //送信バッファー int(32bit)配列
    unsigned char ac[256+1];
    
    unsigned char *c;
    
    int s[2];
    
    s[0] = -2;    //センサーの値
    s[1] = -3;    //センサーの値

    printf("[%d],[%d]\n",s[0],s[1]);

    c = (unsigned char *)(&s[0]);
    
    memcpy(ac, c, (sizeof s)); 
    
    printf("[%x][%x][%x][%x]\n",ac[0],ac[1],ac[2],ac[3]);
    printf("[%x][%x][%x][%x]\n",ac[4],ac[5],ac[6],ac[7]);


    unsigned char *p;
    p = (unsigned char *)(&s[0]);

    memcpy(p, ac, (sizeof s));

    printf("\n");
    printf("[%d],[%d]\n",s[0],s[1]);
    
}




START
[-2],[-3]
[fe][ff][ff][ff]
[fd][ff][ff][ff]

[-2],[-3]


1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?