JAVA/C#/C/C++ 整數(x32 int) 互轉 位元組/位元(byte/bit)

JAVA/C#/C/C++ 整數(x32 int) 互轉 位元組/位元(byte/bit)

JAVA/C#/C/C++ 整數(x32 int) 互轉 位元組/位元(byte/bit)


單晶片節省記憶體儲存資料應用技巧


C/C++ 線上編譯: https://www.tutorialspoint.com/compile_c_online.php

C# 線上編譯: https://dotnetfiddle.net/


Code:

/* Online C Compiler and Editor */
#include <stdio.h>

int main()
{
    int i,j,Q,R,v;
    v=1;
    int intbuf[]={1,2,3,4,5,6,7,8,9,10,13,14,15,16};
    unsigned char bytrbuf[2]={0x00};//BYTE
    for(i=0;i<sizeof(intbuf)/sizeof(int);i++)
    {
        bytrbuf[0] = (intbuf[i] & 0xFF); // Get the lower byte
        bytrbuf[1] = ((intbuf[i] >> 8) & 0xFF); // Get the higher byte
        printf("%X %X\n",bytrbuf[1],bytrbuf[0]);
    }

    int value = (bytrbuf[1] << 8) | bytrbuf[0];
    printf("\n%d\n",value);
    return 0;
}

2 thoughts on “JAVA/C#/C/C++ 整數(x32 int) 互轉 位元組/位元(byte/bit)

  1. JAVA/C#/C/C++ int 和 2個BYTE 相互/互相 轉換 [整數 VS HEX字串]
    單晶片寫法


    using System;

    public class Program
    {
    public static void Main()
    {
    int value = 300; // Example int value

    byte lowByte = (byte)(value & 0xFF); // Get the lower byte
    byte highByte = (byte)((value >> 8) & 0xFF); // Get the higher byte

    string byteString = $"{highByte:X2}{lowByte:X2}";
    Console.WriteLine(byteString);

    value = (highByte << 8) | lowByte;
    Console.WriteLine(value);
    }
    }

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *